Home » Programming / Coding

Select Top N Rows Per Group – MS SQL

3 April 2010 4,971 views One Comment

Select Top N Rows Per Group – MS SQL. This code below works with MS SQL 2005 or newer.

–Create a temp table

DECLARE @temp table
(
id int,
groupID int,
groupName varchar(150)
)

–insert sample data for testing

INSERT INTO @temp VALUES(1,1,’A')
INSERT INTO @temp VALUES(2,1,’A')
INSERT INTO @temp VALUES(3,1,’A')
INSERT INTO @temp VALUES(4,1,’A')
INSERT INTO @temp VALUES(5,2,’B')
INSERT INTO @temp VALUES(6,2,’B')
INSERT INTO @temp VALUES(7,2,’B')
INSERT INTO @temp VALUES(8,2,’B')
INSERT INTO @temp VALUES(9,2,’B')
INSERT INTO @temp VALUES(10,2,’B')
INSERT INTO @temp VALUES(11,3,’C')
INSERT INTO @temp VALUES(12,3,’C')

–With Common Table Expression sort them grouped by groupId

WITH CTE AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY groupID ORDER BY ID) AS ‘RowNo’,
ID, groupID, groupName
FROM @TT
)

–Select first 2 items per groupId

SELECT ID,CategoryGroupID,CategoryGroupName
FROM CTE
WHERE RowNo <= 2

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 1.00 out of 5)
Loading ... Loading ...

One Comment »

  • Dejan said:

    Great example, but how could I get random N rows in total but the same number from each group?

    Let’s say N=3, result would be:
    (4,1,’A’)
    (5,2,’B’)
    (12,3,’C’)

    If N=5, the result would look like that (cannot return the same number from each group)
    (2,1,’A’)
    (1,1,’A’)
    (7,2,’B’)
    (9,2,’B’)
    (11,3,’C’)

    Thanks

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.