SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Select the latest records from GROUP BY query
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

pkovarik
Starting Member

Czech Republic
6 Posts

Posted - 02/26/2014 :  08:50:27  Show Profile  Reply with Quote
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

582 Posts

Posted - 02/26/2014 :  09:37:39  Show Profile  Reply with Quote

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

maunishq
Yak Posting Veteran

Canada
71 Posts

Posted - 02/26/2014 :  10:47:01  Show Profile  Reply with Quote
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

India
52317 Posts

Posted - 02/27/2014 :  02:46:07  Show Profile  Reply with Quote

SELECT *
FROM
(
SELECT a1, ..., an, [time], id
		,MAX([time]) OVER (PARTITION BY id) AS MaxTime
	FROM T
)t
WHERE MaxTime = [time]


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000