SQL window functions in CTEs
Compute the window function in a CTE or derived table, then filter on its alias outside, the standard workaround for the WHERE restriction.
- 类别
- 窗口
- Returns
filtered rows- In this category
- 36 of 79
语法
WITH r AS (SELECT ..., ROW_NUMBER() OVER (...) AS rn FROM t) SELECT * FROM r WHERE rn = 1
引擎支持
| 引擎 | 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
WITH r AS (
SELECT order_id, customer_id, amount,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn
FROM orders
)
SELECT order_id, customer_id, amount
FROM r WHERE rn = 1;
值得了解
- WHERE runs before windows, HAVING after grouping but still before windows, JOIN ON before both; none of them can see a window alias. SELECT and the outer ORDER BY can.
- A derived table works the same as a CTE; the CTE is preferred for readability and lets several filters reference the same computed column.
- You can filter on another window function in the outer query too: compute rn and cnt in the CTE, then WHERE rn <= cnt / 2 outside (impossible in one pass).
Questions about Window Functions in CTEs
Can I use a window function in WHERE if I repeat it?
No. SELECT x, RANK() OVER (...) ... WHERE RANK() OVER (...) = 1 is still invalid. The parser rejects any window function outside SELECT and the final ORDER BY; wrap it.
Can the outer query have its own window functions?
Yes: the outer SELECT can rank or aggregate the CTE's output again; two-level windows are the standard way to do 'window of a window'.
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.