Which rows pass the running total filter?
The query sorts items by quantity DESC, id ASC and calculates a running total of quantity. A separate window sum calculates the total number of units across all items. The rows are then filtered using WHERE. Which rows remain in the result?
Predict the resultDuplicates 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 |
Query
WITH ranked AS (
SELECT
id,
quantity,
SUM(quantity) OVER (
ORDER BY quantity DESC, id ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS cumulative_units,
SUM(quantity) OVER () AS all_units
FROM iv_order_items
)
SELECT id, quantity, cumulative_units
FROM ranked
WHERE 5 * (cumulative_units - quantity) < 3 * all_units
ORDER BY quantity DESC, id ASC