Write SQL to return the top N rows inside each category, team, or customer group.
Answer
Use a ranking window function partitioned by the group key and ordered by the metric, then filter the generated rank in an outer query. ROW_NUMBER returns exactly N rows per group, while RANK or DENSE_RANK can include additional tied rows depending on the business rule.
Strong answer includes
- partitions ranking by group
- chooses ROW_NUMBER versus RANK or DENSE_RANK deliberately
- uses deterministic ordering when an exact row count is required
Practical example
Dialect · Portable SQLRuntime · SQLite sample DB
Runs against the resettable SQLite sample database used by the playground.
SQL
Result
Run the query to see the result.
Partition by the group, order by the metric, then filter the generated row number. Use RANK or DENSE_RANK when tied metric values should all qualify.
Expected result: Up to N rows per group, or more when the chosen rank function intentionally includes ties.