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

Viewed 79

I have to return the most recent row in a SQL database, grouped by CallID. The 'most recent' in this instance means the most recent DepartureDate and the highest Departuretime (int) on that date. See below example for your reference:

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

What I want to return for the above, is the below two records:

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

You can use the row_number window function to order the records per callid and then just take the first:

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

You can use a trick with 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...) will restart the row numbering for each CallId. So there are many rows with a 1 marking the highest. TOP 1 would pick just the first row of the result set, but with WITH TIES it will return all first rows, if there are more than one.

Related