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
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