Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Top 5 of each distinct column value

Lets say there was a dataset like this

Grp   | Name (Unique)
A     | Joe
B     | Bob
C     | Jill
B     | James

If there were about 50 of each group (A,B,C) how do I return a result with only the top 5 from each group without doing something like this

SELECT TOP 5 * FROM TABLE WHERE Grp = 'A' UNION ALL
SELECT TOP 5 * FROM TABLE WHERE Grp = 'B' UNION ALL
SELECT TOP 5 * FROM TABLE WHERE Grp = 'C'
like image 627
Control Freak Avatar asked Feb 21 '13 04:02

Control Freak


1 Answers

Try

SELECT Grp, Name FROM(
 SELECT Grp, Name, RANK() OVER (Partition By Grp ORDER By Name DESC) as rankname
   FROM YourTable)
    WHERE rankname <= 5

Edit: I think this is what you want. If it's not, just comment and we can work on it.

like image 161
Scotch Avatar answered Sep 27 '22 20:09

Scotch