Top N per group (with ties)
You need the first N rows of each group: the three priciest products of each category, the two best sellers of each month. Number the rows inside each group with a window function, then keep the first N.
SELECT category_id, name, unit_price
FROM (
SELECT category_id, name, unit_price,
RANK() OVER (PARTITION BY category_id ORDER BY unit_price DESC) AS rnk
FROM products
) ranked
WHERE rnk <= 3
ORDER BY category_id, rnk;
The function decides what happens to ties. ROW_NUMBER gives 1, 2, 3, 4 and always returns exactly N rows; RANK
gives 1, 2, 2, 4 and keeps every row tied at the cut; DENSE_RANK gives 1, 2, 2, 3: the rows at the N highest values.
The trap. ROW_NUMBER on an ORDER BY with ties picks among the tied rows arbitrarily: a product at the same
price as the third one disappears, and not always the same one. Take RANK or DENSE_RANK when ties should stay, or
add a unique tie-breaker (ORDER BY unit_price DESC, product_id) when you need exactly N rows.
On your warehouse. Snowflake, BigQuery, Databricks and DuckDB skip the subquery: QUALIFY RANK() OVER (…) <= 3.
Postgres has no QUALIFY: keep the subquery there, or a LATERAL subquery with ORDER BY … LIMIT 3 per category.
SELECT category_id, name, unit_price,
ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY unit_price DESC, product_id) AS row_num,
RANK() OVER (PARTITION BY category_id ORDER BY unit_price DESC) AS rnk,
DENSE_RANK() OVER (PARTITION BY category_id ORDER BY unit_price DESC) AS dense_rnk
FROM products
WHERE category_id IN (4, 15)
QUALIFY dense_rnk <= 3
ORDER BY category_id, unit_price DESC, product_id;
| category_id | name | unit_price | row_num | rnk | dense_rnk |
|---|---|---|---|---|---|
| 4 | Ethiopia Moka 1 kg | 31.90 | 1 | 1 | 1 |
| 4 | Colombia Huila 1 kg | 27.90 | 2 | 2 | 2 |
| 4 | Peru Organic 1 kg | 27.90 | 3 | 2 | 2 |
| 4 | House Espresso 1 kg | 26.50 | 4 | 4 | 3 |
| 15 | Chemex 6 cups | 52.00 | 1 | 1 | 1 |
| 15 | AeroPress | 39.00 | 2 | 2 | 2 |
| 15 | Filter carafe 600 ml | 34.00 | 3 | 3 | 3 |
| 15 | Moka pot 6 cups | 34.00 | 4 | 3 | 3 |