Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
rowter
Yak Posting Veteran
76 Posts |
Posted - 2013-07-11 : 16:21:11
|
Hi,I have a table that has picktime, route_id, stlat and stlong columns.There might be multiple records having same picktime and routeid.Select S.pickup_time, S.route_id from STARTTBL as S where Start_Dt= '7/11/2013' group by S.Route_id(pktime) route_id stlat stlat08:50 17 -32.01 102.9809:50 17 -33.01 102.9814:25 2516:30 2516:00 291. Is it possible to get the all the 4 columns where pickup_time is MAX for each Route_idFor the above data , the resulting data would be09:50 17 -33.01 102.9816:30 2516:00 29Thanks |
|
MuMu88
Aged Yak Warrior
549 Posts |
Posted - 2013-07-11 : 16:25:30
|
quote: Originally posted by rowter Hi,I have a table that has picktime, route_id, stlat and stlong columns.There might be multiple records having same picktime and routeid.Select MAX(S.pickup_time), S.route_id from STARTTBL as S where Start_Dt= '7/11/2013' group by S.Route_id(pktime) route_id stlat stlat08:50 17 -32.01 102.9809:50 17 -33.01 102.9814:25 2516:30 2516:00 291. Is it possible to get the all the 4 columns where pickup_time is MAX for each Route_idFor the above data , the resulting data would be09:50 17 -33.01 102.9816:30 2516:00 29Thanks
[CODE]WITH CTE AS(Select MAX(S.pickup_time) as pickup_time, S.route_id from STARTTBL as S where Start_Dt= '7/11/2013' group by S.Route_id)SELECT * from CTE T1 LEFT JOIN STARTTBL T2 WHERE T1.route_id = T2.route_id and T1.pickup_time = T2.pickup_time;[/CODE] |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-07-12 : 01:56:06
|
Assuming picktime is of datatype time you can useSELECT *FROM (SELECT ROW_NUMBER() OVER (PARTITION BY route_id ORDER BY pktime DESC) AS Seq,*FROM table)tWHERE Seq=1 ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-07-12 : 01:58:46
|
if its varchar you need this small modificationSELECT *FROM (SELECT ROW_NUMBER() OVER (PARTITION BY route_id ORDER BY DATEDIFF(minute,0,pktime) DESC) AS Seq,*FROM table)tWHERE Seq=1 ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
|
|
|
|
|