SQL Server 2012,选择两个最大记录然后加入

时间:2017-10-09 16:36:26

标签: sql sql-server max left-join

我尝试进行使用公共ScheduledObjectID字段的多表连接。我想根据max RunID和UserDueDate从表中选择多个记录。任何帮助将不胜感激。

示例数据:

ScheduledObjectID RunID   UserDueDate
-------------------------------------------------
123               1       2017-07-16 14:26:56.263
123               2       2017-05-16 14:26:56.250
123               3       2017-05-16 14:26:56.233
456               9       2017-05-16 14:26:56.217
456               10      2017-05-16 14:26:56.200
456               11      2017-10-07 10:19:33.873

所需的加入数据

ScheduledObjectID RunID   UserDueDate
-------------------------------------------------
123               3       2017-05-16 14:26:56.233
456               11      2017-10-07 10:19:33.873

1 个答案:

答案 0 :(得分:0)

无需加入,您可以使用带有关系的前1名

demo here

select top 1 with ties ScheduledObjectID, RunID,   UserDueDate
from
#tmp 
order by 
row_number() over (Partition by ScheduledObjectID order by runid desc)

根据评论,这应该有效:

select * from t1 join
(select ScheduledObjectID,max(runid) as runid,max(userduedate) as userduedate
from t2

按计划对象分组     )t2     在t1.somecol1 = t2.somecol