Monthly Running Total

A medium SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
medium
Seniority
L5

Problem

We track transaction-level sales and want a per-product ledger where each month shows that month's sales beside a cumulative total that carries forward from the product's earliest month onward. Present it product by product from the lowest id upward, walking each product's months in calendar order, and leave out any transaction that isn't tied to a product.

Cumulative sales per product across months.

Tables

transactions

Columns: transaction_id INTEGER, product_id INTEGER, total_amount REAL, transaction_date TEXT, user_id INTEGER, quantity INTEGER

transactions: 10 of 200 rows
transaction_iduser_idproduct_idquantitytotal_amounttransaction_date
10671971001223.462026-02-02
11342941050336.932026-03-03
12013911099450.42026-04-04
12684881148563.872026-05-05
13355851197002026-06-06
14026821246290.812026-07-07
146977912953104.282026-08-08
153687613444117.752026-09-09
160397313935-452026-01-10
1670107014421144.692026-02-11

Expected output

First 5 of 182 rows
product_idmonthmonthly_totalcumulative_total
10012022-0123.4623.46
10012026-0223.4646.92
10012026-08225.51272.43
10502023-0236.9336.93
10502026-0336.9373.86

Worked solution and explanation

Why this problem exists in real interviews

Querying transactions for total_amount data using grouping and running total tests whether you can translate a business requirement into the right column references and filter sequence. It shows up in mid-level screens to verify practical fluency.


Break down the requirements

Step 1: Apply the window function

CTE monthly: filter transactions to product_id IS NOT NULL (excludes unattributed rows), then SUM(total_amount) grouped by product_id and the YYYY-MM month bucket.

Step 2: Aggregate with SUM

Outer query: a cumulative window SUM(monthly_total) OVER (PARTITION BY product_id ORDER BY month) accumulates monthly totals across months within each product.

Step 3: Order the final output

ORDER BY product_id, month gives the deterministic by-product-then-month ordering the prose requires.


The solution

Nested SUM with cumulative window frame
WITH monthly AS (
  SELECT
    product_id,
    strftime('%Y-%m', transaction_date) AS month,
    SUM(total_amount) AS monthly_total
  FROM transactions
  WHERE product_id IS NOT NULL
  GROUP BY product_id, strftime('%Y-%m', transaction_date)
)
SELECT
  product_id,
  month,
  monthly_total,
  SUM(monthly_total) OVER (PARTITION BY product_id ORDER BY month) AS cumulative_total
FROM monthly
ORDER BY product_id, month

Common follow-up questions