SQL aggregates with OVER window
Window aggregates compute a group statistic but hand it to every row instead of collapsing the group.
- Returns
same as the aggregate- In this category
- 44 of 52
语法
SUM(x) OVER (PARTITION BY g) | SUM(x) OVER (ORDER BY d)
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | Supported under this name. |
| Oracle | 是 | Supported under this name. |
示例
Any engine
SELECT order_id, SUM(total) OVER (PARTITION BY customer_id) AS lifetime FROM orders;
PostgreSQL
SELECT order_id, SUM(total) OVER (ORDER BY order_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM orders;
SQL Server
SELECT AVG(total) OVER (PARTITION BY customer_id) AS avg_order FROM orders;
值得了解
- Unlike GROUP BY, the window form never collapses rows: detail and total sit side by side.
- With ORDER BY in the OVER clause, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so rows with tied ORDER BY values all get the same total; use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for a strict running total.
- PARTITION BY without ORDER BY gives the group total on every row of the partition.
- SUM over an all-NULL window returns NULL, not 0.
Questions about OVER
OVER vs GROUP BY for SUM?
GROUP BY returns one row per group; OVER keeps every row and annotates it with the group statistic.
Why does my running total jump?
The default RANGE frame includes peer rows with equal ORDER BY values; switch to ROWS for one-row-at-a-time totals.
Do NULLs count in window aggregates?
The same rules as plain aggregates: NULLs are skipped and an all-NULL window returns NULL for SUM and AVG.
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.