Laufende Summe
The SUM you already know, plus an OVER clause that leaves the rows in place and adds a growing sum.
The task
You want a cumulative revenue column next to each order, in date order, without a self-join or a loop.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT order_date, id, amount,
SUM(amount) OVER (ORDER BY order_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM orders
ORDER BY order_date, id;
So funktioniert es
SUM with OVER (ORDER BY ...) accumulates from the first row up to the current one. The explicit ROWS frame makes the total strictly row-by-row; the default RANGE frame would also include any peer rows that share the current ORDER BY value, which surprises people. The window's ORDER BY decides the accumulation order and the outer ORDER BY only decides display, so keep them identical or the running total will look like it jumps around.
Variations
Running total per customer
SELECT customer_id, order_date, amount,
SUM(amount) OVER (PARTITION BY customer_id
ORDER BY order_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM orders
ORDER BY customer_id, order_date;
Questions that come up
Why specify ROWS BETWEEN explicitly?
The default frame is RANGE between UNBOUNDED PRECEDING and the current row's peers, so rows tied on the ORDER BY key all enter the sum at once. That is sometimes what you want, but with duplicate dates it makes the total jump and confuses the running-total intent.
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.