The Bestseller Ranking
The storefront at Whetcode Supply has a Bestsellers shelf, and the position on it is printed beside each item rather than left for the shopper to count down the page. Position is decided by units shifted, not by money — a shelf is about what people buy, and the cheap thing everybody buys belongs at the top of it.
Two items have shifted exactly the same number of units, and the shop's rule is that equal sales mean an equal position: they share a number, and the position immediately after it is skipped. A shelf can therefore read 1, 2, 3, 4, 4.
orders — one row per order. customer_id is the id of the customer who placed it, product_id the id of the item bought, quantity how many units of that item, and order_date the day it was placed. An order row covers one item only.
| id | customer_id | product_id | quantity | order_date |
|---|---|---|---|---|
| 1 | 1 | 1 | 2 | 2023-02-01 |
| 2 | 1 | 4 | 1 | 2023-02-01 |
| 3 | 2 | 2 | 1 | 2023-02-10 |
| 4 | 3 | 3 | 3 | 2023-03-05 |
| 5 | 4 | 5 | 5 | 2023-03-11 |
| 6 | 1 | 3 | 1 | 2023-04-02 |
| 7 | 5 | 1 | 4 | 2023-05-20 |
| 8 | 2 | 5 | 2 | 2023-05-22 |
| 9 | 3 | 4 | 1 | 2023-06-01 |
| 10 | 5 | 2 | 1 | 2023-06-15 |
products — the catalogue, one row per item on sale. price is what a single unit costs, in dollars.
| id | name | category | price |
|---|---|---|---|
| 1 | Wireless Mouse | electronics | 25.0 |
| 2 | Standing Desk | furniture | 350.0 |
| 3 | Desk Lamp | furniture | 40.0 |
| 4 | Mechanical Keyboard | electronics | 85.0 |
| 5 | Notebook Set | office | 12.0 |
The tables already exist in the database — there is nothing to create or load.
Task: Write a query returning three columns, name (the product's name), units (the total units of that item sold across every order) and sales_rank (its position on the shelf by units, 1 being the most sold), one row per product that has sold at least once. Two items on the same units share a position and the next position is skipped. Order the rows by sales_rank ascending, and alphabetically by name for two items sharing a position. A product nobody has ordered does not appear at all.
Example output — shape only, on an invented catalogue. The second and third moved the same units, so they share position 2 and position 3 goes unused:
| name | units | sales_rank |
|---|---|---|
| Monitor Riser | 26 | 1 |
| Cable Tidy | 19 | 2 |
| Foot Rest | 19 | 2 |
| Paper Trimmer | 12 | 4 |
| Ink Refill | 8 | 5 |
Sign in to solve this problem
Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.
Sign in