SQL 如何 return 具有最近日期和最高 int 值的记录

SQL How to return the record with the most recent date and also highest int value

我必须 return SQL 数据库中的最新行,按 CallID 分组。本例中的 'most recent' 表示最近的 DepartureDate 和该日期的最高 Departuretime (int)。请参阅以下示例供您参考:

set dateformat dmy
create table #Temp
(
Callid nvarchar(6), 
Linenum nVarchar(6), 
Engineerid nvarchar (4), 
Departuredate DateTime, 
Departuretime int
)
insert into #Temp 
Values (
'100000','1','AToo','05/09/2017','57896'),
('100000','1.5','DBok','05/09/2017','57898'),
('100000','1.75','DBok','05/09/2017','57895'),
('100000','2','GKar','04/09/2017','59805'),
('100000','3','ALee','05/09/2017','54895'),
('100001','1','GKar','08/09/2017','54000'),
('100001','2','GKar','08/09/2017','58895'),
('100001','2.25','ALee','08/09/2017','56875'),
('100001','2.5','DBok','07/09/2017','59000')

select * from #Temp
drop table #Temp

上面我要return的,就是下面两条记录:

CallID  Linenum  Engineerid  Departuredate  Departuretime
100000  1.5      DBok        05/09/2017     57898
100001  2        GKar        08/09/2017     58895

您可以使用 row_number window 函数按 callid 对记录进行排序,然后只取第一个:

SELECT CallID, Linenum, Engineerid, Departuredate, Departuretime
FROM   (SELECT CallID, Linenum, Engineerid, Departuredate, Departuretime,
               ROW_NUMBER() OVER (PARTITION BY CallID
                                  ORDER BY Departuredate DESC, Departuretime DESC) AS rn
        FROM   #Temp) t
WHERE  rn = 1

你可以使用 TOP 1 WITH TIES

的技巧
select TOP 1 WITH TIES * 
from #Temp
ORDER BY ROW_NUMBER() OVER (PARTITION BY CallId ORDER BY Departuredate DESC,Departuretime DESC);

ORDER BY ROW_NUMBER() OVER(PARTITION BY CallId...) 将为每个 CallId 重新开始行编号。所以有很多行带有 1 标记 最高 TOP 1 将只选择结果集的第一行,但是对于 WITH TIES 它将 return 所有 first 行,如果有多个.