return 最近的相邻行,按日期 earlier/later 到另一个 table 的日期

return nearest adjacent rows that are earlier/later by date to another table's date

问题:要return单个结果集基于以下

对于报告中的每个日期 table (rdate) return 早于或等于 rdate (plus t1 & t2) 作为 sdate 的最新交易 table (tdate), s1,s2

对于报告中的每个日期 table (rdate) return 晚于或等于 rdate (加上 t1 & t2) 的最早事务 table (tdate) 作为 edate, e1,e2

已尝试 TOP 1 / APPLY / LEAD& LAG 代码,但无法获得所需的结果。

如有任何建议,我们将不胜感激。谢谢

举报table

rdate
06/01/2021
26/01/2021
15/02/2021

交易table

tdate t1 t2
01/01/2021 17 6
05/01/2021 5 9
09/01/2021 8 12
19/01/2021 15 11
20/01/2021 12 8
25/01/2021 9 1
26/01/2021 8 17
30/01/2021 7 6
08/02/2021 6 21
22/02/2021 14 5
27/02/2021 11 4

需要结果

rdate sdate s1 s2 edate e1 e2
06/01/2021 05/01/2021 5 9 09/01/2021 8 12
26/01/2021 26/01/2021 8 17 26/01/2021 8 17
15/02/2021 08/02/2021 6 21 22/02/2021 14 5

A CROSS APPLYOUTER APPLY 以及具有适当顺序和过滤条件的 SELECT TOP 1 应该可以解决问题。尝试:

DECLARE @ReportTable TABLE (rdate DATETIME)
INSERT @ReportTable
VALUES
    ('2021-01-06'),
    ('2021-01-26'),
    ('2021-02-15')

DECLARE @TransactionTable TABLE (tdate DATETIME, t1 INT, t2 INT)
INSERT @TransactionTable
VALUES
    ('2021-01-01', 17, 6),
    ('2021-01-05', 5, 9),
    ('2021-01-09', 8, 12),
    ('2021-01-19', 15, 11),
    ('2021-01-20', 12, 8),
    ('2021-01-25', 9, 1),
    ('2021-01-26', 8, 17),
    ('2021-01-30', 7, 6),
    ('2021-02-08', 6, 21),
    ('2021-02-22', 14, 5),
    ('2021-02-27', 11, 4)

SELECT * -- TODO: Assign meaningful names here
FROM @ReportTable R
OUTER APPLY (
    SELECT TOP 1 *
    FROM @TransactionTable T1
    WHERE T1.tdate <= R.rdate
    ORDER BY T1.tdate DESC
) S
OUTER APPLY (
    SELECT TOP 1 *
    FROM @TransactionTable T2
    WHERE T2.tdate >= R.rdate
    ORDER BY T2.tdate
) E
ORDER BY R.rdate

OUTER APPLY 类似于 CROSS APPLYLEFT JOIN,允许找不到任何记录。仔细查看不等式条件,以确保边缘情况符合预期。