Ranking, further
Top N per category: compute RANK() OVER (PARTITION BY category ORDER BY …) inside WITH, then WHERE rank <= N outside. With ties, RANK may give a few extra rows, while ROW_NUMBER always gives exactly N. NTILE(4) splits rows into four groups. PERCENT_RANK() is a relative position from 0 to 1.
You met ROW_NUMBER and RANK in the beginner course. This lesson puts them to work on questions a boss really asks: "What are the best sellers in each category?" "How much do the top quarter of customers bring in?" "Who are the top 10% of customers?"
How ties are ranked
In this step you see how the three ranking functions differ when there's a tie. First work out how much each person spent, then rank them three ways, and look only at the middle places:
1WITH spending AS (2 SELECT user_id, SUM(amount) AS spent3 FROM orders4 WHERE status = 'paid'5 GROUP BY user_id6),7ranked AS (8 SELECT user_id, spent,9 ROW_NUMBER() OVER (ORDER BY spent DESC, user_id) AS row_num,10 RANK() OVER (ORDER BY spent DESC) AS rnk,11 DENSE_RANK() OVER (ORDER BY spent DESC) AS dense12 FROM spending13)14SELECT *15FROM ranked16WHERE row_num BETWEEN 15 AND 1917ORDER BY row_num;
| user_id | spent | row_num | rnk | dense |
|---|---|---|---|---|
| 31 | 178 | 15 | 15 | 15 |
| 9 | 172 | 16 | 16 | 16 |
| 14 | 171 | 17 | 17 | 17 |
| 23 | 171 | 18 | 17 | 17 |
| 5 | 162 | 19 | 19 | 18 |
Users 14 and 23 both spent 171:
ROW_NUMBERignores ties: one gets 17, the other 18. Who comes first depends on the second thing inORDER BY,user_id.RANKgives both of them 17, and the next person jumps to 19, just like in a race where two people tie for first and the next one is third.DENSE_RANKalso gives both 17, but the next person is 18: no places are skipped.
| user_id | spent | row_num | rnk | dense |
|---|---|---|---|---|
| 9 | 172 | 16 | 16 | 16 |
| 14 | 171 | 17 | 17 | 17 |
| 23 | 171 | 18 | 17 | 17 |
| 5 | 162 | 19 | 19 | 18 |
The boss asks, "Who's in 18th place for spending?" Which function always gives a place 18 in the result?
RANK skips places after a tie: after the two 17s comes 19, so nobody is 18th. ROW_NUMBER and DENSE_RANK never skip, so there's always an 18. But they give different people: ROW_NUMBER gives user 23, and DENSE_RANK gives user 5. Say in your report which one you used.The top few in each category
In this step you solve the most common ranking question: the best-selling products in each category. First rank by category inside WITH, then pick the ones in place 1 outside:
1WITH product_sales AS (2 SELECT p.category, p.name, SUM(oi.qty) AS qty3 FROM orders AS o4 JOIN order_items AS oi ON oi.order_id = o.id5 JOIN products AS p ON p.id = oi.product_id6 WHERE o.status = 'paid'7 GROUP BY p.category, p.name8),9ranked AS (10 SELECT category, name, qty,11 RANK() OVER (PARTITION BY category ORDER BY qty DESC) AS r12 FROM product_sales13)14SELECT category, name, qty15FROM ranked16WHERE r = 117ORDER BY category, name;
| category | name | qty |
|---|---|---|
| food | Coffee beans | 10 |
| food | Tea box | 10 |
| home | Cushion | 37 |
| office | Desk calendar | 24 |
| office | Notebook | 24 |
| tech | Speaker | 26 |
4 categories, but 6 rows: in food, Coffee beans and Tea box both sold 10, and in office, Desk calendar and Notebook both sold 24, so they tie for first. That's what's good about RANK: a tie never makes one of them quietly disappear. With ROW_NUMBER, each category always gets exactly one row, but which of the two tied products stays depends on the second sort condition you give. If you don't give one, the database picks, and it might pick differently each time you run the query.
Top two by sales in each category
✓Rank the products in each category by sales (qty * price added up) and find the top two in each category. Four columns: category, name, sales and r (the place), sorted by category, then place.
| category | name | sales | r |
|---|---|---|---|
| food | Coffee beans | 300 | 1 |
| food | Tea box | 220 | 2 |
| home | Cushion | 666 | 1 |
| home | Desk lamp | 630 | 2 |
| office | Desk calendar | 288 | 1 |
| office | Notebook | 144 | 2 |
| tech | Headphones | 1680 | 1 |
| tech | Speaker | 1560 | 2 |
1WITH product_sales AS (2 SELECT p.category, p.name, SUM(oi.qty * oi.price) AS sales3 FROM orders AS o4 JOIN order_items AS oi ON oi.order_id = o.id5 JOIN products AS p ON p.id = oi.product_id6 WHERE o.status = 'paid'7 GROUP BY p.category, p.name8)9SELECT category, name, sales10FROM product_sales;
A rank can't go straight into WHERE
In this step you see an error everybody runs into sooner or later. Why do we always wrap the query in an extra WITH? Try putting the rank straight into WHERE:
1SELECT name, price, RANK() OVER (ORDER BY price DESC) AS r2FROM products3WHERE RANK() OVER (ORDER BY price DESC) <= 3;
ERROR 3593 (HY000): You cannot use the window function 'rank' in this context.'
An error. The reason is the order a query runs in: WHERE picks the rows first, and only after that does SELECT work out the ranks. While WHERE is doing its job, the ranks don't exist yet. So you work out the rank first, in a WITH (or a subquery), where it becomes a column, and then the WHERE outside can use it.
Put these lines in order to make a query that runs: the 3 most expensive products.
)SELECT name, priceSELECT name, price, RANK() OVER (ORDER BY price DESC) AS rFROM productsWHERE r <= 3FROM rankedORDER BY r;WITH ranked AS (
name | price Headphones | 80 Speaker | 60 Desk lamp | 35
r in WITH first. Then the outer query can treat r as an ordinary column and pick rows with WHERE r <= 3.Four equal groups
In this step you split people by share. NTILE(4) splits the sorted rows into 4 groups, as evenly as it can, and gives each row a group number from 1 to 4. The quarter who spent the most is group 1:
1WITH spending AS (2 SELECT user_id, SUM(amount) AS spent3 FROM orders4 WHERE status = 'paid'5 GROUP BY user_id6),7quartered AS (8 SELECT user_id, spent,9 NTILE(4) OVER (ORDER BY spent DESC, user_id) AS quarter10 FROM spending11)12SELECT quarter, COUNT(*) AS users, SUM(spent) AS total13FROM quartered14GROUP BY quarter15ORDER BY quarter;
| quarter | users | total |
|---|---|---|
| 1 | 8 | 3248 |
| 2 | 8 | 1580 |
| 3 | 8 | 1135 |
| 4 | 7 | 460 |
31 people bought something, which can't be split into 4 equal groups, so the groups are 8, 8, 8 and 7: the extra people go one per group, starting from group 1. The 8 people in group 1 spent 3248, more than half of the whole year. The last 7 people spent only 460 between them.
If you split 10 rows with NTILE(3), how many rows does each group get?
NTILE never drops a row.The top few percent
In this step you find the top 10% of customers. PERCENT_RANK() gives each row a number from 0 to 1: first place is 0, last place is 1, and the places in between are spread evenly. The formula is (rank - 1) / (rows - 1).
1WITH spending AS (2 SELECT user_id, SUM(amount) AS spent3 FROM orders4 WHERE status = 'paid'5 GROUP BY user_id6),7ranked AS (8 SELECT user_id, spent,9 PERCENT_RANK() OVER (ORDER BY spent DESC) AS pr10 FROM spending11)12SELECT u.name, r.spent, ROUND(r.pr, 2) AS pr13FROM ranked AS r14JOIN users AS u ON u.id = r.user_id15WHERE r.pr <= 0.116ORDER BY r.spent DESC;
| name | spent | pr |
|---|---|---|
| Kai | 556 | 0 |
| Alba | 549 | 0.03 |
| Felipe | 458 | 0.07 |
| Zeca | 405 | 0.1 |
Both NTILE and PERCENT_RANK can split by share. The difference: NTILE only cares about making the groups the same size, so two tied people can land in different groups. PERCENT_RANK uses the places from RANK, so tied people get the same number and always end up on the same side.
Change only the number in the green box to find the top 20% of customers by spending.
1WITH spending AS (2 SELECT user_id, SUM(amount) AS spent3 FROM orders4 WHERE status = 'paid'5 GROUP BY user_id6),7ranked AS (8 SELECT user_id, spent,9 PERCENT_RANK() OVER (ORDER BY spent DESC) AS pr10 FROM spending11)12SELECT user_id, spent13FROM ranked14WHERE pr <= 15ORDER BY spent DESC;
user_id | spent 11 | 556 26 | 549 6 | 458 25 | 405 17 | 369 12 | 351 3 | 292
pr <= 0.2 keeps the people whose relative position is in the top 20%. 20% of 31 people is about 6.2, and 7th place has a pr of 6 / 30 = 0.2: right on the edge, so it stays too.What you learned
- With ties:
ROW_NUMBERforces an order (give it a second sort condition);RANKgives tied rows the same place and skips the places after;DENSE_RANKgives tied rows the same place and skips nothing. - Top N per category: put
RANK() OVER (PARTITION BY category ORDER BY …)in aWITH, thenWHERE rank <= Noutside. WithRANK, ties can add a few extra rows. - A window function can't go in
WHERE(ERROR 3593), becauseWHEREruns beforeSELECT. NTILE(n)splits the rows into n groups as evenly as it can; the extra rows go one each, starting from group 1.PERCENT_RANK()is a relative position from 0 to 1, and<= 0.1means the top 10%. Tied people always end up on the same side.