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
Get the latest row per group
Use ROW_NUMBER in a subquery or CTE.
OpenIn sheetsqlsame section
Return top values including ties
Use RANK when tied rows should all qualify.
OpenIn sheetsqlsame section
ROW_NUMBER
Unique sequence with no ties.
RANK
Tied rows share rank and leave gaps.
DENSE_RANK
Tied rows share rank without gaps.
Split rows into quartiles with NTILE
Bucket ordered rows into four groups.