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.
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
| id | user_id | total | discount | item_count | status | order_date | shipped_date | shipping_city | shipping_country |
|---|---|---|---|---|---|---|---|---|---|
The first rows of each table are shown. See how all the tables relate on the database schema page.
Expected output
| month | revenue | running_total |
|---|---|---|
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:
- Define a common table expression named
monthly:- Read from the
orderstable. - Filter in
WHERE: keep the rows wherestatusis none of 'cancelled' or 'refunded'. - Group the rows by
month(the year-month oforder_date), so the result has one row for each value. - For each group, compute
SUM(total). ROUND()trims the calculated figures to a fixed number of decimals.
- Read from the
- Read from the
monthlyCTE. ROUND()trims the calculated figures to a fixed number of decimals.- A subquery in the SELECT list is evaluated for each output row, using values from that row:
- Read from the
monthlyCTE. - Filter in
WHERE: keep the rows wheremonthis at most the outer row'smonth. - Aggregate over all the rows that are left: compute
SUM(revenue). With no GROUP BY, the result is a single row.
- Read from the
- 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.
Related SQL challenges
- Segment Customers by Recency, Frequency and Monetary Value (RFM)Similar levelHard
- Calculate a Running Median of Order TotalsSimilar levelHard
- Build a Monthly Revenue Report Excluding Cancelled OrdersEasierMedium
- Find the Amount of Each Customer's Most Recent OrderEasierMedium
- Count Orders in Each Customer's First 7 DaysSimilar levelHard
Keep learning
- Lesson: Correlated Subqueries
- Lesson: CTEs (WITH Clause)
- Lesson: GROUP BY
- Lesson: Date Functions
- All SQL practice challenges, by difficulty and topic
- SQL interview questions with answers
- SQL Playground: run any query on the same database