SQL empty OVER ()
An empty OVER () gives every row the aggregate of all rows, the simplest window form and the basis of shares, ratios and totals-inline reports.
- 类别
- 窗口
- Returns
whole-set aggregate- In this category
- 48 of 79
语法
COUNT(*) OVER () | SUM(x) OVER ()
引擎支持
| 引擎 | 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. |
示例
Any engine
SELECT product, price,
price * 1.0 / NULLIF(MAX(price) OVER (), 0) AS price_ratio,
COUNT(*) OVER () AS products_counted
FROM products WHERE stock_qty > 0;
值得了解
- The set is 'all rows of the result after WHERE and GROUP BY'; filters shrink it. An unfiltered denominator needs a separate subquery or CTE.
- Over a GROUP BY query, OVER () covers the groups, not the base rows: COUNT(*) OVER () after grouping counts groups.
- An empty OVER () needs no sort, so adding SUM(x) OVER () next to an ordered window costs little: SUM(x) OVER (ORDER BY d) / SUM(x) OVER () is the cumulative share.
Questions about Empty OVER ()
Is OVER () the same as no OVER?
No: COUNT(*) without OVER collapses to one row; COUNT(*) OVER () keeps every row and repeats the count. Same number, opposite output shapes.
How do I get a total that ignores my WHERE?
Windows see post-filter rows only. Compute the unfiltered total in a scalar subquery or CTE and cross join it.
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.