SQL 连接多个日期

问题描述 投票:0回答:1

我有表 A 和表 B,我试图在货币和日期上进行匹配。当谈到日期时,我只想在同一日期匹配 A 和 B,如果这不起作用,则在一天后匹配。

表A

       DateA      CurrencyA   ID
    2021-12-31        GBP     1
    2022-01-01        GBP     2
    2022-01-02        GBP     3

表B

       DateB      CurrencyB   
    2022-01-01        GBP         
    2022-01-02        GBP

此连接的预期结果应该是

    ID     DateA      DateB       CurrrencyC 
    1    2021-12-31   2022-01-01     GBP
    2    2022-01-01   2022-01-01     GBP
    3    2022-01-02   2022-01-02     GBP

当前结果是

   ID     DateA      DateB       CurrrencyC 
    1    2021-12-31   2022-01-01     GBP
    2    2022-01-01   2022-01-01     GBP
    2    2022-01-01   2022-01-02     GBP
    3    2022-01-02   2022-01-02     GBP

我当前的代码 -

SELECT *
FROM tableA t1
LEFT JOIN tableB t2 ON 
    (t1.date_column = t2.date_column)
    OR 
    (t1.date_column = DATEADD(day, -1, t2.date_column) AND t1.date_column NOT IN (SELECT date_column FROM tableA WHERE date_column = t2.date_column))

我当前的代码目前在多天内都匹配。我该如何解决它?

sql sql-server left-join
1个回答
0
投票

对于每个 tableA 行,您想要找到最佳的 tableB 行。通过横向连接最容易完成此操作:

SELECT *
FROM tableA t1
OUTER APPLY 
(
  SELECT TOP(1)
  FROM tableB t2
  WHERE t2.CurrencyB = t1.CurrencyA
  AND t2.DateB IN (t1.DateA, DATEADD(DAY, 1, t1.DateA)
  ORDER BY t2.DateB
) best_t2
ORDER BY t1.DateA;
© www.soinside.com 2019 - 2024. All rights reserved.