How do you sum item quantities in groups defined by a condition?
The query splits order line items into two categories: many for line items containing at least two units of a product, and one for line items containing exactly one unit. It then adds up the quantities ordered within each category. What numbers will the query return?
Predict the resultGROUP BY / HAVINGJuniorAnalystData EngineerBackendQA
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 |
Query
SELECT CASE
WHEN quantity >= 2 THEN 'many'
ELSE 'one'
END AS size_group,
SUM(quantity) AS units
FROM iv_order_items
GROUP BY CASE
WHEN quantity >= 2 THEN 'many'
ELSE 'one'
END
ORDER BY size_group