SQL · medium
Asked in Data Analyst interviews, in the SQL round.
RANK()/ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) <= 3.
Rank within a partition, then keep ranks up to three.
SELECT category, product_id, revenue
FROM (
SELECT
category,
product_id,
revenue,
DENSE_RANK() OVER (PARTITION BY category ORDER BY revenue DESC) AS rnk
FROM product_revenue
) ranked
WHERE rnk <= 3
ORDER BY category, revenue DESC;
The ranking function is the decision. ROW_NUMBER gives exactly three rows per category and breaks ties arbitrarily; RANK includes ties but can skip ranks (1, 1, 3); DENSE_RANK includes ties and never skips, so "top 3" can return more than three rows when products tie. Say which behaviour the requester wants; there is no default.
If revenue has to be computed first, aggregate in a CTE and rank the aggregate; ranking before aggregating ranks line items, not products.
PARTITION BY, and whether you ask about ties.ORDER BY revenue DESC LIMIT 3, which is top three overall, not per category.