1

I have a PostgreSQL table with 2 fields like the following. Field A is the primary key.

A  | B
------
1  | 1
2  | 1
3  | 1
4  | 1
5  | 2
6  | 2
7  | 2
8  | 2
9  | 2
10 | 3 
11 | 3

I'm looking for a request to get only the 3 first occurrences of B, like this:

A  | B
1  | 1 
2  | 1
3  | 1
5  | 2
6  | 2
7  | 2
10 | 3
11 | 3

Does somebody have a solution?

1 Answers1

2

You want row_number() :

select t.*
from (select t.*, row_number() over (partition by b order by a) as seq
      from table t
     ) t
where seq <= 3;
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52