Rank rows within a category
PARTITION BY restarts the ranking per category; a second window counts the group in the same pass.
The task
You want each product ranked by price within its category, plus how many products the category holds, so you can show '3rd of 25' style labels.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT name, category, price,
RANK() OVER (PARTITION BY category
ORDER BY price DESC) AS rank_in_category,
COUNT(*) OVER (PARTITION BY category) AS products_in_category
FROM products
ORDER BY category, rank_in_category;
Fonctionnement
PARTITION BY category makes both window functions restart from row one in every category. RANK orders products by price inside the partition; the unordered COUNT window counts every row in the partition, giving the group size without a second query. Ties share a rank, which is usually what a leaderboard wants.
Variations
Rank with dense levels and a percentage
SELECT name, category, price,
DENSE_RANK() OVER (PARTITION BY category
ORDER BY price DESC) AS rank_in_category,
ROUND(100.0 * RANK() OVER (PARTITION BY category
ORDER BY price DESC)
/ COUNT(*) OVER (PARTITION BY category), 1) AS percentile_in_category
FROM products
ORDER BY category, rank_in_category;
Questions that come up
Why not GROUP BY category?
GROUP BY collapses each category to one row and throws away the individual products. Window functions rank the rows and keep them, which is exactly the leaderboard shape.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.