Running total of daily revenue
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Write a query that returns, for every day that has orders, the day's revenue and the running total of revenue up to and including that day.
Return the columns order_date, daily_revenue and running_total, ordered by order_date. Days without orders don't appear.
Example
orders
| id | order_date | amount |
|---|---|---|
| 1 | 2024-01-01 | 100.00 |
| 2 | 2024-01-01 | 50.00 |
| 3 | 2024-01-02 | 30.00 |
| 4 | 2024-01-04 | 20.00 |
Result:
| order_date | daily_revenue | running_total |
|---|---|---|
| 2024-01-01 | 150.00 | 150.00 |
| 2024-01-02 | 30.00 | 180.00 |
| 2024-01-04 | 20.00 | 200.00 |
Tip
First get one row per day, then add them up in date order. A window function can wrap an aggregate.
Schema
CREATE TABLE orders (
id INT PRIMARY KEY,
order_date DATE NOT NULL,
amount NUMERIC(10, 2) NOT NULL
);Approach
Two steps in one query. GROUP BY collapses the orders to one row per day, then a window function sums the daily totals in date order:
SELECT
order_date,
SUM(amount) AS daily_revenue,
SUM(SUM(amount)) OVER (ORDER BY order_date) AS running_total
FROM orders
GROUP BY order_date
ORDER BY order_date;SUM(SUM(amount)) looks odd, but it reads inside out: the inner SUM is the GROUP BY aggregate (the day's revenue), and the outer SUM ... OVER is the window function, which runs after grouping. With a CTE it's more explicit:
WITH daily AS (
SELECT order_date, SUM(amount) AS daily_revenue
FROM orders
GROUP BY order_date
)
SELECT order_date, daily_revenue,
SUM(daily_revenue) OVER (ORDER BY order_date) AS running_total
FROM daily
ORDER BY order_date;The window frame
OVER (ORDER BY x) means "from the first row up to the current row". Its default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and RANGE treats rows with the same x as peers. Skip the GROUP BY, and two orders on the same day both show the day's full total instead of an increasing sum. Use ROWS BETWEEN ... when you want row-by-row behavior.
Follow-ups
- Running total per customer: add
PARTITION BY customer_id. - 7-day moving average:
AVG(daily_revenue) OVER (ORDER BY order_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), after filling missing days withgenerate_series.
Reference solution
SELECT
order_date,
SUM(amount) AS daily_revenue,
SUM(SUM(amount)) OVER (ORDER BY order_date) AS running_total
FROM orders
GROUP BY order_date
ORDER BY order_date;