Module 5 · Advanced queries

Practice: choose between subqueries and CTEs

By the end you will be able to compare a summary with an average calculated on that summary.

About 25 min

0 of 52 lessons

Before you start, you need

Break queries into steps with CTEs · Turn a summary into a table with a subquery in FROM · Answer questions with subqueries

The problem

You want to find customers whose non-cancelled order total is above the average of those sums. You need two different steps: add up per customer, then calculate the average of the sums.

A CTE lets you name the first list, with one row per customer who has non-cancelled orders. A subquery gets the average of those sums. The final query keeps the customers above it.

This is not the same as averaging individual orders. For example, if one customer adds up to 100 and another to 300, the average of their sums is 200, even if one has more orders than the other. Each summary row counts once.

Prepare and check each step separately. Then compare with the average. In the challenge you will do the same with stock per category: first decide what a row of the summary represents.

How to think about it

What is the difference between the average per order and the average of the per-customer sums?

  • Prepare one row per customer with the sum of their valid orders.
  • Calculate the average over those sums: each customer in the summary counts once.
  • Compare each sum with the average. In the stock challenge, change the unit to the category before getting the threshold.

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

Compare each customer's sum with the average

Not started

Create customer_totals with customer_id and, as valid_total, the sum of non-cancelled orders rounded to two decimal places. Include only customers with non-cancelled orders. Return customer_id and valid_total where it exceeds AVG(valid_total) from the same CTE. Sort by valid_total descending and customer_id ascending.

Expected result: 3 rows with the columns customer_id, valid_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

Compare groups with a helper value

Not started

Create a CTE called inventory with category and SUM(stock) as units. Show category and units for the groups below that CTE's average of units.

Expected result: 4 rows with the columns category, units, in that order. Row order does not matter.

View tables and data

Open this panel to see the full data.

Key takeaways

  • The CTE defines the intermediate table.
  • The subquery gets a helper value.
  • The unit of the summary determines which average you are measuring.

Next: Combine results with UNION