首页 > 解决方案 > SQL 根据日期从历史表中选择一个值

问题描述

我有两张表,一张表(表A)包含用户的支付数据,另一张表(表B)包含用户的排名历史。

Table A
IDNO   LName   FName  Start_Date   PayType     Current_Rank
------------------------------------------------------------
SJ01   Smith   John   11/13/2016   Cert             AC
DJ01   Doe     Jack   10/20/2020   Assignment       BC

Table B
IDNO  Date       Rank
----------------------
SJ01  10/01/2010  CAP
SJ01  10/01/2016  BC
SJ01  10/01/2020  AC
DJ01  01/01/2010  LT
DJ01  01/01/2015  CAP
DJ01  01/01/2020  BC

我需要根据表 A 中的 start_date 显示用户的排名,并从表 B 中引入排名。所以我的最终结果可能如下所示:

IDNO   LName   FName  Start_Date   PayType         Rank
------------------------------------------------------------
SJ01   Smith   John   11/13/2016   Cert             BC
DJ01   Doe     Jack   10/20/2020   Assignment       BC    

如何加入这两个表并比较日期,以便我可以根据表 A 中的 start_date 从历史表中引入排名?

标签: sqlsql-server

解决方案


这是一种方法:

select a.* , c.Rank From TableA a
cross apply (select top 1 * from tableB b
        where a.IdNo = b.IDno 
        and a.Start_Date > b.date
        order by b.date desc
     ) c

推荐阅读