SQL服务器:对于table1中的每条记录,在table2中找到最接近的匹配

SQL Server: For each record in table 1, find the closest match in table 2

我有 2 个 tables。

table1

date1, closingprice

table2

 date2, strikeprice, ask

对于 table 1 中的每条记录,我想匹配 table1.date1 = table2.date2 - 4 以找到最接近 table1.closingpricetable1.closingprice > table2.strikepricetable2.strikeprice

对于 table1 中的每条记录,其中日期与 table2 中的日期匹配,table2 中有多个记录。但根据上述约束,我只对 table2 中的 1 条记录感兴趣。

我要table2.date2strikeprice,在输出结果中从table2询问。

我使用 table1.date1 = DATEADD(DD, -4, table2.date2) 匹配日期,效果很好...

关于如何尽可能简单地做到这一点有什么想法吗?对正在发生的事情的解释将不胜感激。我看过一个 CROSS APPLY 的例子,但对任何容易理解的例子以及它为什么有效....

持开放态度

谢谢,

您可以join并使用相关子查询进行过滤:

select t1.*, t2.strikeprice
from table1 t1
inner join table2 t2 
    on t1.date1 = dateadd(DD, -4, t2.date2)
    and t2.strikeprice = (
        select max(strikeprice)
        from table2 t22
        where t22.date2 = t2.date2
        and t22.strikeprice < t1.closingprice
    )

这假设 table2(date2, strikeprice) 上没有重复项;否则,您可能会在结果集中得到重复项。不过,这个假设似乎与您的问题一致。