HardSQL challenge #191CTEWITHCorrelated SubqueryRunning Total

Monthly Revenue Running Total with a CTE and Correlated Subquery

Show revenue per month and a cumulative total, written without window functions.

The challenge runs on the SQLabHub practice database (SQLite) and uses the orders table. You can solve it in the browser, with nothing to install.

Solve This SQL Challenge

The task

Show monthly revenue with a running cumulative total using a subquery.

A correct answer returns 36 rows with 3 columns: month, revenue, running_total.

Tables used in this challenge

orders 200 rows

id INTEGER (PK) · user_id INTEGER · total REAL · discount REAL · item_count INTEGER · status TEXT · order_date TEXT · shipped_date TEXT · shipping_city TEXT · shipping_country TEXT

First 3 rows of the orders table
iduser_idtotaldiscountitem_countstatusorder_dateshipped_dateshipping_cityshipping_country
1432638.110.253cancelled2024-04-24NULLLos AngelesUSA
2829470.195delivered2024-03-152023-04-09ChicagoUSA
3136683.240.082delivered2023-02-152023-07-10Los AngelesUSA

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
monthrevenuerunning_total
2022-0123317.7723317.77
2022-021015.5424333.31
2022-032948.727282.01
2022-0413322.6940604.7
2022-054341.1444945.84

First 5 of 36 rows. This is the output of the model solution on the practice database.

What you practise

  • Filtering rows with a WHERE condition
  • Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
  • Grouping rows with GROUP BY to get one result row per group
  • Writing a subquery that refers to the current row of the outer query
  • Naming an intermediate result with a WITH clause and reading from it
  • Working with dates in SQLite: strftime, julianday and DATE
  • Sorting the result with ORDER BY

Hint and approach

Try the challenge first. Open these only when you need them.

Show the hint

Use a correlated subquery to sum all months up to and including each month

Show the step-by-step approach

How the model solution is built, in the order the database evaluates it:

  1. Define a common table expression named monthly:
    1. Read from the orders table.
    2. Filter in WHERE: keep the rows where status is none of 'cancelled' or 'refunded'.
    3. Group the rows by month (the year-month of order_date), so the result has one row for each value.
    4. For each group, compute SUM(total).
    5. ROUND() trims the calculated figures to a fixed number of decimals.
  2. Read from the monthly CTE.
  3. ROUND() trims the calculated figures to a fixed number of decimals.
  4. A subquery in the SELECT list is evaluated for each output row, using values from that row:
    1. Read from the monthly CTE.
    2. Filter in WHERE: keep the rows where month is at most the outer row's month.
    3. Aggregate over all the rows that are left: compute SUM(revenue). With no GROUP BY, the result is a single row.
  5. Sort the result by month.

Model solution

Checking your session…

What to watch for

The CTE reduces orders to one row per month. For each month the subquery re-adds every month up to and including it, which is quadratic work; SUM(revenue) OVER (ORDER BY month) does it in one pass and is what you would use where window functions exist.

  • Correlated subquery. A correlated subquery is evaluated per outer row, which gets slow on large tables. A join to a grouped subquery or a window function usually does the same work in one pass.
  • CTE (WITH). A CTE exists only for the single statement it is attached to. It is not a temporary table and cannot be reused by the next query.
  • GROUP BY. Every selected column must either be in GROUP BY or sit inside an aggregate. SQLite accepts other columns and returns an arbitrary value for them; most databases raise an error.
Solve This SQL Challenge

Keep learning