Top N per group

Top N per group retrieves the first N rows of each group, for example the 3 best products per category. You number the rows with ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) in a CTE or derived table, then filter on the rank. LIMIT alone cannot do it.

Example

WITH t AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY categorie ORDER BY ca DESC) AS rn FROM produits
)
SELECT * FROM t WHERE rn <= 3;

Related concepts

The whole glossary