Interview Questions/SQL/Running Total Revenue per Customer

Running Total Revenue per Customer

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a table of customer purchases. Each purchase has a customer ID, an amount, and a date. Write a SQL query that returns every purchase row enriched with a running_total column: the cumulative sum of amount for that customer up to and including the current row, ordered by purchase_date. Return all columns (id, customer_id, amount, purchase_date, running_total), ordered by customer_id then purchase_date. Table: Purchases

Column NameTypeDescription
idINTPrimary key
customer_idINTID of the customer
amountINTPurchase amount
purchase_dateDATEDate of the purchase

Database Schema (Inferred)

Purchases

Column NameExample Value
id1
customer_id1
amount100
purchase_date2023-01-05

Example

Purchases

idcustomer_idamountpurchase_date
111002023-01-05
212002023-02-10
311502023-03-15
423002023-01-20
52502023-04-01
635002023-05-05

Output

idcustomer_idamountpurchase_daterunning_total
111002023-01-05100
212002023-02-10300
311502023-03-15450
423002023-01-20300
52502023-04-01350
635002023-05-05500

Explanation:

Use SUM() as a window function partitioned by customer_id and ordered by purchase_date with ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Purchases

idcustomer_idamountpurchase_date
111002023-01-05
212002023-02-10
311502023-03-15
423002023-01-20
52502023-04-01
635002023-05-05

Output

idcustomer_idamountpurchase_daterunning_total
111002023-01-05100
212002023-02-10300
311502023-03-15450
423002023-01-20300
52502023-04-01350
635002023-05-05500