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

时间:2018-09-10 13:48:50

标签: sql sql-server tsql select top-n

我必须返回SQL数据库中按CallID分组的最新行。在这种情况下,“最近”是指该日期的最新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

我想要返回的是以下两条记录:

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

2 个答案:

答案 0 :(得分:5)

您可以使用row_number窗口函数对每个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

答案 1 :(得分:4)

您可以通过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,它将返回所有 first 行。