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
 Select the latest records from GROUP BY query

Author  Topic 

pkovarik
Starting Member

6 Posts

Posted - 2014-02-26 : 08:50:27
I have a table T (a1, ..., an, time, id). I need to select those rows that have different id (GROUP BY id), and from each "id group" the row that has the latest field 'time'. Something like SELECT a1, ..., an, time, id ORDER BY time DESC GROUP BY id. This is the wrong syntax and I don't know how to handle this.

Ifor
Aged Yak Warrior

700 Posts

Posted - 2014-02-26 : 09:37:39
[code]
WITH TGrp
AS
(
SELECT a1, ..., an, [time], id
,ROW_NUMBER(PARTITION BY id ORDER BY [time] DESC) AS rn
FROM T
)
SELECT a1, ..., an, [time], id
FROM TGrp
WHERE rn = 1
[/code]
Go to Top of Page

maunishq
Yak Posting Veteran

71 Posts

Posted - 2014-02-26 : 10:47:01
It should be ROW_NUMBER() OVER (PARTITION BY id ORDER BY [time] DESC) AS rn

!_(M)_!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-02-27 : 02:46:07
[code]
SELECT *
FROM
(
SELECT a1, ..., an, [time], id
,MAX([time]) OVER (PARTITION BY id) AS MaxTime
FROM T
)t
WHERE MaxTime = [time]
[/code]

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

- Advertisement -