Keep the highest-value rows within each partition.
Section: Top N per group
Get top 3 rows per group
sql
sql
WITH ranked AS (
SELECT product_id,
category_id,
revenue,
ROW_NUMBER() OVER (
PARTITION BY category_id
ORDER BY revenue DESC
) AS rn
FROM product_metrics
)
SELECT *
FROM ranked
WHERE rn <= 3;Explanation
Swap `ROW_NUMBER` for `RANK` or `DENSE_RANK` when ties should be handled differently.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Top N per group