要了解作用域的问题 可先看一下这个问题
https://www.jianshu.com/p/5afccb879b80
那窗口函数的行作用域到底哪些呢?
排名函数
rank、ntile、dense_rank、row_number 行的作用域都是全结果集,且不支持指定 rows_range_clause
聚合函数
count、sum,count,max,min等 都支持指定rows_range_clause 但如果不指定order by 则是全表,指定了order by 则行范围默认就是 RANGE UNBOUNDED PRECEDING AND CURRENT ROW
可以用下面语句试试。
;with abc as
(
select 0 as id union all
select 1 union all
select 2 union all
select 3
)
select id,
sum(id) over(),
count(id)over(),
sum(id) over(order by id),
count(id)over(order by id),
sum(id) over(order by id rows between UNBOUNDED PRECEDING AND UNBOUNDED following ),
count(id)over(order by id rows between UNBOUNDED PRECEDING AND UNBOUNDED following )
from abc
分析函数
lag,lead 都不支持 指定rows_range_clause
LAST_VALUE 、FIRST_VALUE 默认就是 RANGE UNBOUNDED PRECEDING AND CURRENT ROW