Lessons › SQL › Chapter 6: Window Functions
SQL lesson
Top N analysis
LIMIT gives you the top rows of the whole table. But often you want the top in each group: the biggest order in every category. It takes two steps. First, number the rows inside each group, biggest first. Then keep the rows numbered 1 (or 1 to 3 for the top 3).
Try this lesson free →Example
The best in each group
WITH ranked AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY category
ORDER BY revenue DESC
) AS rn
FROM orders
)
SELECT *
FROM ranked
WHERE rn = 1| order_id | category | revenue | rn |
|---|---|---|---|
| O2001 | Electronics | 299.99 | 1 |
| O2005 | Clothing | 210.0 | 1 |
| O2006 | Home | 75.0 | 1 |
Step by step
- Numbers each category's orders 1, 2, 3, biggest first.
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn FROM orders) SELECT * FROM ranked WHERE rn = 1 - WHERE can't use the number while it's being made, so you make it in a CTE first.
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn FROM orders) SELECT * FROM ranked WHERE rn = 1 - Keeps the rows numbered 1: the biggest in each category.
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn FROM orders) SELECT * FROM ranked WHERE rn = 1
Practice
1. Using orders, show the biggest order in each category.
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn FROM orders) SELECT * FROM ranked WHERE rn = 12. Now show the top 2 orders in each category.
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn FROM orders) SELECT * FROM ranked WHERE rn <= 23. Using employees, show the highest-paid employee in each department.
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) SELECT * FROM ranked WHERE rn = 14. Using products, show the cheapest product in each category.
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY price) AS rn FROM products) SELECT * FROM ranked WHERE rn = 15. Using store_sales, show each store's 2 biggest sales.
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY store_id ORDER BY revenue DESC) AS rn FROM store_sales) SELECT * FROM ranked WHERE rn <= 2Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →