// window reference

SQL OVER combined with GROUP BY

When a query has GROUP BY, window functions see the grouped rows: one pass for group aggregates plus totals or trends across groups.

Catégorie
Fenêtre
Returns
per-group rows with window values
In this category
49 of 79

Syntaxe

SELECT g, SUM(x), SUM(SUM(x)) OVER () FROM t GROUP BY g

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Oui Supported under this name.
PostgreSQL Oui Supported under this name.
MySQL Oui MySQL 8.0+
SQLite Oui SQLite 3.25+
Oracle Oui Supported under this name.

Exemples

PostgreSQL

SELECT department, SUM(salary) AS payroll,
       SUM(SUM(salary)) OVER (ORDER BY department) AS cumulative_payroll,
       100.0 * SUM(salary) / SUM(SUM(salary)) OVER () AS payroll_share
FROM employees
GROUP BY department
ORDER BY department;

Bon à savoir

  • The nested-looking SUM(SUM(x)) is correct: the inner SUM(x) is the GROUP BY aggregate, the outer one windows over the group results. SUM(x) OVER () fails here because x is neither grouped nor aggregated.
  • PARTITION BY / ORDER BY in the window must reference grouped columns or aggregates of them; referencing a raw non-grouped column errors.
  • This ordering (WHERE, then GROUP BY, then windows, then outer ORDER BY) is also why HAVING cannot filter window results.

Questions about OVER with GROUP BY

Why SUM(SUM(x)) OVER () and not SUM(x) OVER ()?

After GROUP BY, the rows the window sees are groups, and a raw x no longer exists in them; SUM(x) OVER () is rejected for the same reason SELECT x would be. The double SUM is idiomatic, not a typo.

Can I window over groups and filter groups too?

HAVING filters groups before windows compute, so HAVING sees SUM(x) but not window results. Wrap in a CTE to filter on the windowed values.

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.