AnalystPath

Top Three Sellers per Warehouse

SQLHardSenior level~15 min

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.

products
product_idproduct_nameunits_soldwarehouse_id
1Stapler851
2Lamp802
3Mug602
warehouses
warehouse_idwarehouse_name
1North
2South

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

Related SQL questions