Start learning free

LESSON 6 OF 66 · SQL: BEYOND THE BASICS

One CTE on Top of Another in Python

Practice

One WITH can hold several CTEs, separated by commas, and a later one can read an earlier one as if it were a table. Each stage of the job gets its own name, and the whole query reads top to bottom: first this, then that, then the answer.

WITH cheap AS (
    SELECT name, category FROM products WHERE price < 10
),
cheap_counts AS (
    SELECT category, COUNT(*) AS n FROM cheap GROUP BY category
)
SELECT category, n FROM cheap_counts ORDER BY n DESC

Three rules: there is only one WITH; a comma goes after every CTE's closing bracket except the last; and the main SELECT comes right after the last bracket. A CTE lives only inside its query, and the query may read it more than once, for example in FROM and again in a subquery inside WHERE. That's handy, because WHERE checks one row at a time and can't use AVG directly.

The first CTE, order_totals, is given: one row per order, with its id, customer_id and total. Summed per customer, the order totals give four rows (customer 5 has none):

customer_id | spent
1 | 75
2 | 38
3 | 89
4 | 73

Their average is 68.75. The check prints your query's rows with show(db, query), and it must print only the customers above that average:

customer_id | spent
1 | 75
3 | 89
4 | 73
(3 rows)

Your task: add a second CTE, customer_totals, that sums total from order_totals into spent for each customer_id. Then write the main query: customer_id and spent from customer_totals, keeping the customers whose spent is above the average spent.


Assignment
Follow the Coding Tutorial to add the second CTE under the first one, then the main query that reads it.


Hint
No second WITH: the first CTE's ), already has the comma. Work out the average with a subquery in brackets that reads customer_totals again, and compare spent with it.


STEP 1 OF 7
    Ctrl + Enter to check

    Sqlx Cte Chain in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free