Which row will ROW_NUMBER keep for each product?
The query selects one record per product. Look at the sort order inside the window function and determine which rows will remain in the result.
Predict the resultDuplicates and top NJuniorAnalystData 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
SELECT product, id, price
FROM (
SELECT product, id, price,
ROW_NUMBER() OVER (
PARTITION BY product
ORDER BY price DESC, id ASC
) AS rn
FROM iv_order_items
) AS ranked
WHERE rn = 1
ORDER BY product