Get the Top 5 of each distinct column value

sql-server, sql-server-2008, t-sql

Solution

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.

Problem

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' ```

Original source