Find the bugs: Order number and total orders per customer
For each order with a known customer_id, return its id, customer_id, its position in that customer's order sequence, and the total number of orders the customer has placed. Number the orders by created_at; if two orders share a timestamp, the one with the smaller id comes first. Review the SQL and select the lines containing errors.
Find the errorsWindow functionsMiddleAnalystData EngineerBackend
Input data · iv_orders
| id | customer_id | status | created_at | total |
|---|---|---|---|---|
| 1 | 1 | paid | 2026-01-15 10:00:00 | 100.00 |
| 2 | 1 | paid | 2026-01-31 23:59:00 | 50.00 |
| 3 | 2 | paid | 2026-02-01 00:00:00 | 200.00 |
| 4 | 2 | cancelled | 2026-02-10 12:30:00 | 75.50 |
| 5 | 3 | paid | 2026-02-28 23:59:59 | 30.00 |
| 6 | NULL | paid | 2026-03-01 00:00:00 | 60.00 |
| 7 | 5 | new | 2026-03-05 09:15:00 | 120.00 |
| 8 | 1 | paid | 2026-03-31 18:00:00 | 80.00 |
SELECT id,
customer_id,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY created_at, id
) AS order_no,
MAX(ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at, id))
OVER (PARTITION BY customer_id) AS total_orders
FROM iv_orders
WHERE customer_id IS NOT NULL
ORDER BY customer_id, id