Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

I need to take the first N rows for each group, ordered by a custom column.

Given the following table:

db=# SELECT * FROM xxx;

 id | section_id | name

----+------------+------

  1 |          1 | A

  2 |          1 | B

  3 |          1 | C

  4 |          1 | D

  5 |          2 | E

  6 |          2 | F

  7 |          3 | G

  8 |          2 | H

(8 rows)

I need the first 2 rows (ordered by name) for each section_id, i.e. a result similar to:

 id | section_id | name

----+------------+------

  1 |          1 | A

  2 |          1 | B

  5 |          2 | E

  6 |          2 | F

  7 |          3 | G

(5 rows)

I am using PostgreSQL 8.3.5.

1 Answer

0 votes
by (40.7k points)

For PostgreSQL 8.4, You can use the below code:

SELECT * 

FROM (SELECT ROW_NUMBER() OVER (PARTITION BY section_id ORDER BY name) AS r,t.* FROM xxx t) x

WHERE x.r <= 2;

Related questions

+3 votes
1 answer
0 votes
1 answer
asked Dec 27, 2020 in SQL by Appu (6.1k points)
0 votes
1 answer

Browse Categories

...