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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Select MAX value for each ID, with date tiebreaker
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

unCANny
Starting Member

USA
2 Posts

Posted - 05/18/2012 :  19:57:03  Show Profile  Reply with Quote
So to make this more interesting I have to cast strings to integers first in order to derive the "MEASUREMENT" column. Then I have to get the MAX value of the MEASUREMENT column for each ID, However in this scenario they are likely to be tied, so in that case I need to get the row with the latest DATE.

SELECT ID, LEVEL, DATE, CAST(CASE
WHEN LEVEL = 'high' THEN 3
WHEN DETECTION = 'medium' THEN 2
WHEN DETECTION = 'low' THEN 1
END AS INT) AS MEASUREMENT
FROM TABLE


Here's an example table

ID | DATE | MEASUREMENT | LEVEL
______________________________________________________________________
1 | 10/2/2010 | 2 | medium
1 | 3/6/2011 | 2 | medium
1 | 7/4/2010 | 1 | low
2 | 3/6/2009 | 3 | high
1 | 10/2/2010 | 2 | medium
1 | 10/2/2010 | 1 | low


The Output that I desire is :

ID | DATE | MEASUREMENT | LEVEL
______________________________________________________________________
1 | 10/2/2010 | 2 | medium
2 | 3/6/2009 | 3 | high


I appreciate any help you can manage.

Thanks

unCANny
Starting Member

USA
2 Posts

Posted - 05/18/2012 :  20:39:51  Show Profile  Reply with Quote
I got it!

SELECT DISTINCT ID, DATE, MEASUREMENT, LEVEL
FROM (SELECT RANK() OVER (PARTITION BY id ORDER BY MEASUREMENT desc, DATE) as rank_order, ID, DATE, MEASUREMENT, LEVEL
FROM TABLE ) a
WHERE a.rank_order = 1
Go to Top of Page

jsmith8858
Dr. Cross Join

USA
7423 Posts

Posted - 05/22/2012 :  13:14:42  Show Profile  Visit jsmith8858's Homepage  Reply with Quote
Well done, and thank you for showing your solution so it might help others.

- Jeff
http://weblogs.sqlteam.com/JeffS
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.05 seconds. Powered By: Snitz Forums 2000