Skip to content
Advertisement

Pagination with grouping

I have a table with over 800K records. This table needs to be “grouped by” a certain column. An example would be:

enter image description here

However, with pagination, things get complicated. I want to show 50 rows for every group.

This means that if I have the following data:

Id Color Name
1 Red Paper #1
2 Red Paper #2
3 Red Paper #3
4 Green Paper #4
5 Green Paper #5
6 Green Paper #6
7 Green Paper #7

And I wanted to get 2 items for every group per page (instead of 50, for the sake of this example), on page 1 I’d have:

Id Color Name
1 Red Paper #1
2 Red Paper #2
4 Green Paper #4
5 Green Paper #5

And at page 2 I’d have:

Id Color Name
3 Red Paper #3
6 Green Paper #6
7 Green Paper #7

My current SQL query (SQL Server) for pagination is the following:

Advertisement

Answer

Using this sample data:

This query will do:

Page 1: http://sqlfiddle.com/#!18/748cc2/27/0 enter image description here

Page 2: http://sqlfiddle.com/#!18/748cc2/25/0 enter image description here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement