开窗函数是数据开发面试的必知必会,必须认真对待,上难度:
开窗函数语法格式如下,一共五部分:
①函数(a)over(②<partition by b> ③<order by c> ④<windowing_clause> ⑤开窗范围)
1、函数:聚合函数,sum(a)、avg(a)、lag(a,n,null)、lead(a,n,null)、max(a)等
2、分组:partition by b
3、排序:order by c
4、开窗子句:range、rows、Specifying
range:排序字段有相同值时,开窗结果相同
rows:排序字段有相同值时,开窗结果不同
使用开窗子句一定要有排序!!
5、开窗范围:between…and…
between m preceding and n following --当前行的前m行到当前行的后n行
between unbounded preceding and current row --第一行到当前行
–unbounded:不受控制的,无限的
–preceding:在…之前
–following:在…之后
–current row:当前行
以上为理论,以下为实际案例
————————————————-————
1、简单求和
sum(a)
2、累加和
sum(a)over(order by b)
3、分组求和
sum(a)over(partition by c order by b)
4、第一行到当前行分组求和(排序数据重复时,分析函数数据重复)
sum(a)over(partition by c order by b range between unbounded
preceding and current row)
5、第一行到当前行分组求和(排序数据重复时,分析函数数据不重复)
sum(a)over (partition by c order by b rows between unbounded preceding and current row)
6、第一行到当前行前一行求和
sum(a)over(partition by c order by b range between unbounded
preceding and 1 preceding)
7、第一行到当前行后一行求和
sum(a)over(partition by c order by b range between unbounded preceding and 1 following)
8、当前行前80行到当前行求和
sum(a)over(partition by c order by b range between 79 preceding and current row)