Top Three Sellers per Warehouse
Problem
A retailer ranks products by units sold within each warehouse.
Table: `products`
| Column | Type |
|---------------|---------|
| product_id | int |
| product_name | varchar |
| units_sold | int |
| warehouse_id | int |
`product_id` is the primary key; `warehouse_id` references `warehouses.warehouse_id`.
Table: `warehouses`
| Column | Type |
|---------------|---------|
| warehouse_id | int |
| warehouse_name| varchar |
`warehouse_id` is the primary key.
A product is a **best seller** in its warehouse if its `units_sold` is among the **top three distinct** unit-sold values for that warehouse. Several products may share a unit-sold value, and a tied value counts as one of the three distinct levels.
Return the best sellers as three columns named `warehouse`, `product`, and `units`, in any order. No two products in the same warehouse share the same name and units.
Tables
Example rows — the live problem includes the full dataset.
| product_id | product_name | units_sold | warehouse_id |
|---|---|---|---|
| 1 | Stapler | 85 | 1 |
| 2 | Lamp | 80 | 2 |
| 3 | Mug | 60 | 2 |
| warehouse_id | warehouse_name |
|---|---|
| 1 | North |
| 2 | South |
Expected output
Your answer should return 6 rows with the columns warehouse, product, units.
Starter code (SQL)
SELECT *
FROM products;Solve this SQL question free
Write SQL and run it instantly in your browser — even on your phone. No signup needed to try.
Solution & explanation
Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.
Sign up free to unlock