SQL running total
SUM(x) OVER (ORDER BY d) accumulates from the first row to the current one: a cumulative total without a self-join.
- 카테고리
- 창
- Returns
numeric- In this category
- 31 of 79
구문
SUM(x) OVER (ORDER BY d) | SUM(x) OVER (PARTITION BY g ORDER BY d)
엔진 지원
| 엔진 | Support | 메모 |
|---|---|---|
| SQL Server | 예 | Supported under this name. |
| PostgreSQL | 예 | Supported under this name. |
| MySQL | 예 | MySQL 8.0+ |
| SQLite | 예 | SQLite 3.25+ |
| Oracle | 예 | Supported under this name. |
예시
Any engine
SELECT day, amount,
SUM(amount) OVER (ORDER BY day) AS balance
FROM ledger;
Any engine
-- per-account balance, strict row order
SELECT account_id, day, amount,
SUM(amount) OVER (PARTITION BY account_id ORDER BY day, id
ROWS UNBOUNDED PRECEDING) AS balance
FROM ledger_entries;
알아 두면 좋은 정보
- ORDER BY is what turns the sum into a running one; with only PARTITION BY you get the partition's grand total on every row.
- The default frame is RANGE, so tied ORDER BY values all show the total including every peer. Switch to ROWS UNBOUNDED PRECEDING if each row must see only strictly earlier rows.
- The ORDER BY must be deterministic (add a tiebreaker) or the running values can permute between tied rows run to run.
Questions about Running Total
Why is my running total wrong for tied dates?
The default RANGE frame includes all peers of the current row, so tied rows share one subtotal. Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to sum strictly row by row.
How do I restart the running total per group?
PARTITION BY the group inside OVER: SUM(x) OVER (PARTITION BY account_id ORDER BY day). Each partition accumulates from its own first row.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.