Units Moved
The warehouse at Whetcode Supply reorders stock from a single sheet: for each item, how many units have gone out of the door in total. Fast movers sit at the top, because those are the lines that run out first and the ones worth phoning a supplier about.
The sheet is worked from item numbers rather than names — the shelves are labelled with numbers and the picker never sees the catalogue. Two items have shifted the same number of units, so the sheet also needs a rule for what happens when totals are equal.
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 |
The table already exists in the database — there is nothing to create or load.
Task: Write a query returning two columns, product_id and units (the total number of units of that item across every order), one row per item that has been ordered at least once, most units first. When two items have the same total, put the smaller product_id first. An item nobody has ever ordered does not appear at all, not even with a zero.
Example output — shape only, on invented items. The last two moved the same number of units, so the smaller product_id goes first:
| product_id | units |
|---|---|
| 11 | 24 |
| 12 | 18 |
| 13 | 15 |
| 14 | 9 |
| 16 | 9 |
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