Find the bugs: total value of orders containing a specific product
Find all orders that contain at least one pen item. For each matching order, calculate the total value of all its items using SUM(quantity * price), including any other products. Return order_id and order_value, sorted by order_id in ascending order. Which lines in the query are incorrect?
Find the errorsQuery execution orderMiddleAnalystData 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 order_id,
SUM(quantity * price) AS order_value
FROM iv_order_items
WHERE product = 'pen'
GROUP BY order_id
HAVING SUM(CASE WHEN product = 'pen' THEN 1 ELSE 0 END) > 0
ORDER BY order_id