按日期获取加入订单的最新记录

Getting the record with latest record on join order by date

考虑两个这样的 table

id  name 
1   john  
2   doe
3   jan

device id   id  devicename     purchasedate
1           1    iphone         2018-02-22
2           1    iphone2        2019-02-22  
3           1    iphone3        2020-02-22
4           2    iphone4        2019-02-22
5           2    iphone5        2019-02-25
6           3    iphone6        2020-03-15

所以结果必须是两个 table 的连接,并且只有记录的最新购买日期必须 selected。所以预期的 select 结果将是这样的,如果第一个 table 中有一条记录与第二个 table 中没有关系,则不应如此 selected只能使用内连接。

id name device id device name 
1  john    3        iphone3
2  doe     5        iphone5
3  jan     6        iphone6

你可以cross apply:

select t1.name, t2.* -- or whatever columns you want
from table1 t1 cross apply
     (select top (1) t2.*
      from table2 t2
      where t2.id = t1.id
      order by t2.purchaseddate desc
     ) t2