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 |
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 TGrpAS( SELECT a1, ..., an, [time], id ,ROW_NUMBER(PARTITION BY id ORDER BY [time] DESC) AS rn FROM T)SELECT a1, ..., an, [time], idFROM TGrpWHERE rn = 1[/code] |
|
|
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)_! |
|
|
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)tWHERE MaxTime = [time][/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
|
|
|
|
|