PostgreSQL中的分组限制:显示每组的前N行?

我需要为每个组取前N行,按自定义列排序。


鉴于下表:


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)

我需要每个section_id的前2行(按名称排序),即类似于的结果:


 id | section_id | name

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

  1 |          1 | A

  2 |          1 | B

  5 |          2 | E

  6 |          2 | F

  7 |          3 | G

(5 rows)

我正在使用PostgreSQL 8.3.5。


摇曳的蔷薇
浏览 875回答 3
3回答

富国沪深

新解决方案(PostgreSQL 8.4)SELECT&nbsp; *&nbsp;FROM (&nbsp; SELECT&nbsp; &nbsp; ROW_NUMBER() OVER (PARTITION BY section_id ORDER BY name) AS r,&nbsp; &nbsp; t.*&nbsp; FROM&nbsp; &nbsp; xxx t) xWHERE&nbsp; x.r <= 2;

POPMUISE

这是另一个解决方案(PostgreSQL <= 8.3)。SELECT&nbsp; *FROM&nbsp; xxx aWHERE (&nbsp; SELECT&nbsp; &nbsp; COUNT(*)&nbsp; FROM&nbsp; &nbsp; xxx&nbsp; WHERE&nbsp; &nbsp; section_id = a.section_id&nbsp; AND&nbsp; &nbsp; name <= a.name) <= 2
打开App,查看更多内容
随时随地看视频慕课网APP