Find the bugs: Top two products by units sold
A store wants to find the two products with the highest number of units sold. The number of units sold is stored in quantity, so you need to sum the quantities across all order items. If two products have the same total, the product whose name comes first alphabetically should rank higher. The query runs, but the sales totals are incorrect. Where's the mistake?
Find the errorsDuplicates and top NMiddleAnalystData EngineerBackend
Input data · iv_order_items
| id | order_id | product | quantity | price |
|---|---|---|---|---|
| 1 | 1 | pen | 10 | 2.00 |
| 2 | 1 | notebook | 1 | 10.00 |
| 3 | 2 | pen | 1 | 4.00 |
| 4 | 3 | notebook | 5 | 10.00 |
| 5 | 3 | bag | 1 | 50.00 |
| 6 | 4 | pen | 2 | 3.00 |
| 7 | 5 | pen | 3 | 10.00 |
| 8 | 7 | bag | 2 | 60.00 |
| 9 | 8 | notebook | 2 | 40.00 |
SELECT product, SUM(quantity) AS units
FROM (
SELECT product, quantity
FROM iv_order_items
ORDER BY quantity DESC, id ASC
LIMIT 2
) AS selected_items
GROUP BY product
ORDER BY units DESC, product