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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 sql query using group by

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 stlat
08:50 17 -32.01 102.98
09:50 17 -33.01 102.98
14:25 25
16:30 25
16:00 29

1. Is it possible to get the all the 4 columns where pickup_time is MAX for each Route_id

For the above data , the resulting data would be

09:50 17 -33.01 102.98
16:30 25
16:00 29

Thanks

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 stlat
08:50 17 -32.01 102.98
09:50 17 -33.01 102.98
14:25 25
16:30 25
16:00 29

1. Is it possible to get the all the 4 columns where pickup_time is MAX for each Route_id

For the above data , the resulting data would be

09:50 17 -33.01 102.98
16:30 25
16:00 29

Thanks



[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]
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-07-12 : 01:56:06
Assuming picktime is of datatype time you can use


SELECT *
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY route_id ORDER BY pktime DESC) AS Seq,*
FROM table
)t
WHERE Seq=1


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-07-12 : 01:58:46
if its varchar you need this small modification

SELECT *
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY route_id ORDER BY DATEDIFF(minute,0,pktime) DESC) AS Seq,*
FROM table
)t
WHERE Seq=1


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -