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.
- 카테고리
- 창
- Returns
per-group rows with window values- In this category
- 49 of 79
구문
SELECT g, SUM(x), SUM(SUM(x)) OVER () FROM t GROUP BY g
엔진 지원
| 엔진 | 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. |
예시
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;
알아 두면 좋은 정보
- 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.
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.