← All SQL interview questions
Top two revenue positions per category
MediumWindow FunctionsAmazonWalmart
A category head wants the top two products by total revenue in every category. If two products tie, they share the same position and the next position is not skipped, so a tie can return more than two rows for a category.
From product_sales, return category, product_name, total_revenue and rnk for products ranked 1 or 2 within their category. Order by category, rnk, then product_name.
Sample data
Table: product_sales
17 row(s) · showing first 8
| sale_idINT | product_nameTEXT | categoryTEXT | revenueNUMERIC(10,2) |
|---|---|---|---|
| 1 | Earbuds | Electronics | 12000.00 |
| 2 | Earbuds | Electronics | 8000.00 |
| 3 | Smartwatch | Electronics | 15000.00 |
| 4 | Smartwatch | Electronics | 5000.00 |
| 5 | Power Bank | Electronics | 9000.00 |
| 6 | Webcam | Electronics | 4000.00 |
| 7 | Webcam | Electronics | 2500.00 |
| 8 | Air Fryer | Home | 18000.00 |
product_sales
- sale_idINT
- product_nameTEXT
- categoryTEXT
- revenueNUMERIC(10,2)
- Step 1: Sum revenue per product first, because each product has several sale rows.
- Step 2: `DENSE_RANK()` gives tied products the same rank and does not skip the next one. `RANK()` would give Power Bank rank 3 in Electronics and drop it; `ROW_NUMBER()` would arbitrarily drop one of the tied products.
- Step 3: Filter `rnk <= 2` in the outer query because window results cannot be filtered in the same `SELECT`.
WITH product_totals AS (
SELECT category, product_name, SUM(revenue) AS total_revenue
FROM product_sales
GROUP BY category, product_name
),
ranked AS (
SELECT category, product_name, total_revenue,
DENSE_RANK() OVER (
PARTITION BY category
ORDER BY total_revenue DESC
) AS rnk
FROM product_totals
)
SELECT category, product_name, total_revenue, rnk
FROM ranked
WHERE rnk <= 2
ORDER BY category, rnk, product_name;More Window Functions questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program