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

Why this question comes up

The finance team tracks cumulative revenue against the annual target: each month's takings and the running total so far. This version uses a subquery, which is how it is done on databases without window functions.

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
143321.680.259cancelled2024-04-24NULLDelhiIndia
2810.520.191delivered2024-03-152024-03-20ColumbusUSA
3136181.190.085delivered2023-02-152023-02-18ChicagoUSA

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-011717.311717.31
2022-021071.742789.05
2022-03643.483432.53
2022-041082.154514.68
2022-05473.194987.87

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
  • Matching a column against a list of values with IN
  • 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.
Show the model solution
WITH monthly AS (
  SELECT SUBSTR(order_date, 1, 7) AS month,
         ROUND(SUM(total), 2) AS revenue
  FROM orders
  WHERE status NOT IN ('cancelled','refunded')
  GROUP BY month
)
SELECT month, revenue,
       ROUND((
         SELECT SUM(m2.revenue)
         FROM monthly m2
         WHERE m2.month <= m1.month
       ), 2) AS running_total
FROM monthly m1
ORDER BY month;

This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.

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.

Another way to solve it

SUM() OVER (ORDER BY month) builds the running total in one pass instead of re-adding all earlier months for every row. Same output; on long histories the window version is far cheaper.

Show the alternative query
WITH monthly AS (
  SELECT SUBSTR(order_date, 1, 7) AS month,
         ROUND(SUM(total), 2) AS revenue
  FROM orders
  WHERE status NOT IN ('cancelled','refunded')
  GROUP BY month
)
SELECT month, revenue,
       ROUND(SUM(revenue) OVER (ORDER BY month), 2) AS running_total
FROM monthly
ORDER BY month;

Checked when this page was built: it returns the same rows as the model solution on the practice database.

Solve This SQL Challenge

Keep learning