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
 help with max and grouping

Author  Topic 

dibblejon
Starting Member

36 Posts

Posted - 2012-07-24 : 11:03:28
Hi

I have a table that has info like:

account | date | reason

abc001 2012-07-01 00:00:00 1
abc001 2012-07-03 14:00:26 3
abc001 2012-07-06 14:00:00 2
sac870 2012-07-01 00:00:00 1
sac870 2012-07-23 00:00:00 2

I want to get results by using a max on the date and returning the reason associated with that group - so for the exanple above I just want to see - the oldest records grouped by account

abc001 2012-07-06 14:00:00 2
sac870 2012-07-23 00:00:00 2

Any help would be great

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-07-24 : 11:12:40
[code]
SELECT account,[date],reason
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY account ORDER BY [date] DESC) AS Rn,*
FROM table
)t
WHERE rn=1
[/code]

if sql 2000 or before use
[code]
SELECT t.*
FROM table t
INNER JOIN (SELECT account,MAX([date]) AS MaxDate
FROM table
GROUP BY account
)t1
ON t1.account = t.account
AND t1.MaxDate = t.[date]
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -