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.
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
- 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.
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.
Related SQL challenges
- Count Orders in Each Customer's First 7 DaysSimilar levelHard
- Find the Week with the Highest RevenueSimilar levelHard
- Calculate Monthly Revenue with strftimeEasierMedium
- Build a Monthly Revenue Report Excluding Cancelled OrdersEasierMedium
- Find the Amount of Each Customer's Most Recent OrderEasierMedium
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