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 one record from each group

Author  Topic 

pkovarik
Starting Member

6 Posts

Posted - 2014-01-21 : 07:01:33
I have for example a table with columns name, surname, id, ..., weight, age. I need to choose from each age group (GROUP BY age) entire record of the person who has the greatest weight. How to construct such a query? Thank you.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-21 : 07:24:08
[code]
SELECT name, surname, id, ..., weight, age
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY age ORDER BY weight DESC) AS Rn,*
FROM table
)t
WHERE Rn = 1
[/code]
If there are mutiple persons with same max weight value with same age and you want all of them to be returned then just replace ROW_NUMBER with DENSE_RANK in the above query

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

- Advertisement -