概念
MySQL中的使用窗口函数的时候,是不允许使用*的,必须显式指定每一个字段。8.0后才有Window Function,其他数据库貌似一早就有
窗口函数有点像聚合函数,an aggregate operation groups query rows into a single result row, a window function produces a result for each query row
普通聚合函数
1 |
|
窗口函数
1 |
|
执行方式
Window functions are permitted only in the select list and ORDER BY clause. Query result rows are determined from the FROM clause, after WHERE, GROUP BY, and HAVING processing, and windowing execution occurs before ORDER BY, LIMIT, and SELECT DISTINCT.
窗口函数
一般的聚合函数可以作为窗口函数
非聚合窗口函数
1 |
|
语法
1 |
|
OVER (window_spec)
1 |
|
- partition_clause
PARTITION BY
子句指示如何将查询行分区,执行窗口函数的结果是基于该分区的所有行,没有PARTITION BY
代表所有行是一个单独分区。
- frame_clause
frame当前分区的子集 帧是根据当前行确定的,这使得帧能够在分区内移动,具体取决于其分区内当前行的位置 => 就是移动窗口
1 |
|
只有聚合函数和FIRST_VALUE() LAST_VALUE() NTH_VALUE()
可以使用,其他的用了会被ignore,use the entire partition even if a frame is specified
1 |
|
OVER window_name
1 |
|
按名称引用窗口,可以更简单地编写查询
1 |
|
子句中使用以不同方式修改窗口
1 |
|
CTE
CTE有两种用法,非递归的CTE和递归的CTE。
非递归的CTE可以用来增加代码的可读性,增加逻辑的结构化表达。
1 |
|