// window reference

SQL SUM with OVER

Sums the window frame or partition and keeps every row: group totals without GROUP BY, and the denominator for percent-of-total queries.

Categoria
Janela
Returns
numeric
In this category
23 of 79

Sintaxe

SUM(x) OVER (PARTITION BY g) | SUM(x) OVER () | SUM(CASE WHEN c THEN x END) OVER (PARTITION BY g)

Suporte a mecanismos

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

Exemplos

Any engine

SELECT region, amount,
       SUM(amount) OVER (PARTITION BY region) AS region_total,
       SUM(amount) OVER () AS grand_total
FROM sales;

Any engine

-- only closed deals count toward the pipeline total
SELECT deal_id, amount, status,
       SUM(CASE WHEN status = 'closed' THEN amount END) OVER (PARTITION BY rep) AS closed_total
FROM deals;

Bom saber

  • SUM returns NULL when the frame has no non-NULL rows; wrap in COALESCE if downstream arithmetic needs 0.
  • SUM(CASE WHEN ...) OVER (...) is the portable FILTER: per-partition conditional totals on SQL Server, MySQL and Oracle before 23.26.1, which lack the FILTER clause.
  • Inside a GROUP BY query, SUM(SUM(x)) OVER () sums the aggregated values: the inner SUM aggregates rows, the outer one windows over the groups.

Questions about SUM OVER

How do I mix SUM OVER with GROUP BY?

Window functions evaluate after grouping, so SUM(SUM(x)) OVER (PARTITION BY dim) works: inner SUM per group, outer SUM across groups. The window's PARTITION BY must name grouped columns.

Does WHERE change what SUM OVER adds up?

Yes. WHERE removes rows before windows run, so SUM(x) OVER () totals only the surviving rows. To keep a row in the output but out of the total, leave it in and put the condition inside the aggregate with FILTER or CASE.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

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