Cumulative total by month
Group to months first, then a running SUM over the monthly totals.
The task
You want revenue per month plus a year-to-date running total. Doing the running sum over raw order rows mixes granularities and gives the wrong chart.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
WITH monthly AS (
SELECT DATE_TRUNC('month', order_date)::date AS month,
SUM(amount) AS month_total
FROM orders
GROUP BY 1
)
SELECT month, month_total,
SUM(month_total) OVER (ORDER BY month) AS cumulative_total
FROM monthly
ORDER BY month;
Cómo funciona
The CTE collapses orders into one row per month. The window SUM then runs over those monthly rows, so each month's cumulative total is the sum of all earlier months plus itself. Aggregating first also makes missing months explicit if you fill them from a calendar spine before the window runs.
Variations
SQL Server month key
SQL ServerWITH monthly AS (
SELECT DATEFROMPARTS(YEAR(order_date), MONTH(order_date), 1) AS month,
SUM(amount) AS month_total
FROM orders
GROUP BY DATEFROMPARTS(YEAR(order_date), MONTH(order_date), 1)
)
SELECT month, month_total,
SUM(month_total) OVER (ORDER BY month) AS cumulative_total
FROM monthly
ORDER BY month;
Questions that come up
Why aggregate to months before the running sum?
A running sum over raw rows gives one value per order, so you would still have to pick each month's last row to chart it. Aggregating first leaves the window 12 rows a year instead of one per order, and each row is already the month-end figure.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.