Module 5 · Advanced queries

Practice: master window functions

By the end you will be able to choose the first row of each group among the supported rows.

About 25 min

0 of 52 lessons

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

Not started

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.

Challenge

Solve this variation. Spot the part that has changed before you look for help.

Practice

Choose the most recent valid order

Not started

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.

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.