Home > Database > Mysql Tutorial > How to Select the Top N Rows per Group Ordered by a Specific Column in PostgreSQL?

How to Select the Top N Rows per Group Ordered by a Specific Column in PostgreSQL?

Susan Sarandon
Release: 2025-01-15 11:19:45
Original
211 people have browsed it

How to Select the Top N Rows per Group Ordered by a Specific Column in PostgreSQL?

Group restriction in PostgreSQL: Select top N rows in each group sorted by custom column

In order to retrieve the top N rows in each group based on a custom column order, PostgreSQL provides a solution for users (especially those using PostgreSQL 8.4 and above).

Consider the example table containing the columns 'id', 'section_id' and 'name':

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

Based on the data provided, the desired output is to select the first two rows (sorted by 'name') for each 'section_id'.

Solutions for PostgreSQL 8.4 and above

<code class="language-sql">SELECT
  *
FROM (
  SELECT
    ROW_NUMBER() OVER (PARTITION BY section_id ORDER BY name) AS r,
    t.*
  FROM
    xxx t
) x
WHERE
  x.r <= 2;</code>
Copy after login

This advanced solution utilizes the 'ROW_NUMBER()' function with 'PARTITION BY' and 'ORDER BY' clauses to achieve the desired result set. Each row in the 'xxx' table is assigned a rank within its respective 'section_id' group, with rows sorted by 'name'. By subsequent selection based on the condition 'x.r <= 2' we effectively limit the number of rows returned in each group.

The above is the detailed content of How to Select the Top N Rows per Group Ordered by a Specific Column in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template