// window reference

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.

Categoría
Ventana
Returns
numeric
In this category
31 of 79

Sintaxis

SUM(x) OVER (ORDER BY d) | SUM(x) OVER (PARTITION BY g ORDER BY d)

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Sí Supported under this name.
MySQL Sí MySQL 8.0+
SQLite Sí SQLite 3.25+
Oracle Sí Supported under this name.

Ejemplos

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;

Conviene saberlo

  • 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.

// fewer lookups

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.