Before you start, you need
Add sums and averages with OVER · Break queries into steps with CTEs
The problem
You will choose one order per customer. In the guided practice, the highest amount among all their orders wins; in the challenge, the most recent non-cancelled order. Deciding which rows may take part changes which order wins.
Prepare a CTE that numbers the rows per customer. Sort the amount from highest to lowest and use id to break ties. In the outer query, keep position 1.
To find the largest non-cancelled order, exclude cancelled orders before numbering. If you number them all and then discard a cancelled winner, you could lose the customer even though they have other valid orders.
Check the customer who has a cancelled order that would win the numbering if you did not exclude it. That row lets you detect the error. Also remember that a group sum repeated with OVER is not a running total; the extension shows how to calculate one with an ordering.
How to think about it
When should a cancelled order be excluded to choose each customer's largest valid order?
- Exclude cancelled orders before numbering. The window should compare only the orders that could be chosen.
- Calculate a position within each customer. Outside the CTE, keep position = 1.
- Check the customer whose cancelled order is larger than all their valid ones. If you remove the cancelled order after choosing, you could lose that customer.
Guided practice
Getting things wrong is part of learning: you can run your query as many times as you like and nothing is lost. If you get stuck, open a hint (each one reveals a bit more) and save the solution for last.
Guided practice
Choose each customer's largest order
Use a CTE to calculate ROW_NUMBER() per customer_id, ordering the orders by total descending, with id ascending as the tiebreaker. Include every status. In the outer query, keep position = 1 and return customer_id, order_id and total, sorted by customer_id.
Expected result: 10 rows with the columns customer_id, order_id, total, in that order. Keep the row order requested.
View tables and data
Open this panel to see the full data.
Number each customer's orders from the highest total down, and pick the first position in another layer.
Order the window by total DESC, id to get a stable position.
In the outer query, filter WHERE position = 1 and sort by customer_id.
Solution explained
WITH sorted AS (
SELECT customer_id,
id AS order_id,
total,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY total DESC, id
) AS position
FROM orders
)
SELECT customer_id, order_id, total
FROM sorted
WHERE position = 1
ORDER BY customer_id;The CTE calculates the position within each customer, and the outer query filters the row in position 1, which you cannot do with WHERE in the same layer that calculates the window.
Challenge
Solve this variation. Spot the part that has changed before you look for help.
Practice
Choose the most recent valid order
Use a CTE to number each customer's non-cancelled orders by date descending and id descending. Return customer_id, order_id and date for position = 1, sorted by customer_id.
Expected result: 10 rows with columns customer_id, order_id, date, in that order. Respect the requested row order.
This activity uses a copy of the data with extra edge cases. Open the full data before you predict the result.
View tables and data
Open this panel to see the full data.
Change the position criterion: now the most recent date wins, not the amount.
Exclude cancelled orders inside the CTE, before numbering.
ORDER BY date DESC, id DESC inside OVER and position = 1 in the outer query.
Solution explained
WITH valid AS (SELECT customer_id, id AS order_id, date, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY date DESC, id DESC) AS position FROM orders WHERE status <> 'cancelled') SELECT customer_id, order_id, date FROM valid WHERE position = 1 ORDER BY customer_id;The copy adds a recent cancelled order for customer 1. Excluding it inside the CTE makes order 111 their most recent valid order. If you filtered after numbering, customer 1 would disappear.
Key takeaways
- Filter the input before calculating positions, where appropriate.
- A CTE lets you filter on the position after calculating it.
- The partition keeps the lists separate.
- A partition total and a running total are different measures.
Next: Add rows with INSERT
Going further with SQLite: download and run it
Compare customer_total, repeated across the partition, with cumulative, which grows by date and id. The frame ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW includes every earlier row and the current one. This frame is practised in SQLite; it does not run in the teaching lab.
Download the script with the database and ready-made queries. Open an empty SQLite database and import the script. In sqlite3 you can use .read windows-cumulative-sqlite.sql. To run it again, import the file into another empty database.