对与需要求最近几个月的什么,需要用到滑动窗口
语法rows between unbounded preceding and current row
- rows是物理窗口,即根据order by 子句排序后,取的前N行及后N行的数据计算(与当前行的值无关,只与排序后的行号相关)
- range是逻辑窗口,是指定当前行对应值的范围取值,列数不固定,只要行值在范围内,对应列都包含在内
unbounded:*限
preceding:从分区第一行头开始,则为 unbounded。 N为:相对当前行向前的偏移量
following :与preceding相反,到该分区结束,则为 unbounded。N为:相对当前行向后的偏移量
current row:顾名思义,当前行,偏移量为0
如力扣579
现在有一个表员工表,求每个id连续三个月的salary的总和
1.使用rows —rows between unbounded preceding and current row
表示从当前行开始,对当前行的前两行,总计三行进行求和。
select id,month,
sum(salary) over(partition by id order by month rows between 2 preceding and current row) as salary
from employee
得到一张这样的表, 显然不对,因为这里要求连续三个月,七月已经没有连续
2.如果使用range—RANGE between UNBOUNDED PRECEDING AND CURRENT ROW
select id,month,
sum(salary) over(partition by id order by month range between 2 preceding and current row) as salary
from employee