How can we find the top 3 highest-earning employees in each department?
Filtering a ROW_NUMBER() partition window subquery for rn <= 3 retrieves the top N records per category.
Top 3 products per category, highest 3 sales per region, top 3 songs per artist.
SELECT *
FROM (
SELECT
name,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS rn
FROM employees
) ranked
WHERE rn <= 3;Practice typing production-grade SQL code for Top N per Group.