窗口函數

作用

以當前行R爲基準,關聯出若干行mR(窗口),對mR進行聚合,計算出聚合值x,將x附加到R上。

窗口由關鍵字over指定

聚合操作支持所有內置和自定義的聚合函數,還支持幾個特有的函數,如:row_number,rank,lag,lead

本質

替代關聯和子查詢的簡寫語法

窗口範圍指定

全表數據

over():窗口爲全表數據

over( order by B):全表根據B排序,窗口爲全表數據自第0行起,到當前行的全部行

當前行所在分組

over( partition by A):根據列A分組,窗口爲當前行所在分組的全部行

over( partition by A order by B):根據列A分組,然後在組內根據B排序,窗口爲組內第0行至當前行的全部行

 當前行的前後若干行

over( rows between current row and X following):從當前行起,到向後X行

聚合函數

常規的聚合函數,如max,avg,min等等

專用函數:row_number,rank,lag,lead

自定義統計函數

舉例

1、現在有張學生成績表,統計每個學生分數與平均分差距

select *,total_score  -  avg( total_score ) over() as from_avg  from stu_info

2、在上一個基礎上,統計每個學生分數與省內平均分的差距

select *,total_score  -  avg( total_score ) over( partition by bir_place ) as from_avg  from stu_info

3、統計每個學生省內排名

select *, row_number() over( w_place order by total_score desc)  as range_place, total_score  -  avg( total_score ) over( w_place ) as from_avg  from stu_info
window w_place as ( partition by bir_place )

這個例子值得注意的地方是row_number函數的使用,在這種情況下可以用count(*)代替。上面的語句等效於:

select *, count(* )over( w_place order by total_score desc)  as range_place, total_score  -  avg( total_score ) over( w_place ) as from_avg  from stu_info
window w_place as ( partition by bir_place )

因爲:

over( order by B):全表根據B排序,窗口爲全表數據自第0行起,到當前行的全部行

排序後的窗口大小實際上就是排名。

4、統計每個學生與下一名考生的差距

select *,row_number() over( order by total_score desc)  as sRange,  total_score - lead(total_score)over( order by total_score desc )   as from_next from stu_info

這裏需要注意的是,在統計from_next時,由於是按照total_score降序排序的,窗口over( order by total_score desc)其實並不包含下一名考生的成績,但是使用lead(leg同理)可以拓寬窗口。

5、現有銷售表如下,統計累計銷售額

select *,sum(total) over(order by good_name) as gAll from
	(select *,good_price*good_num as total from good_saled_info order by good_num) as tab_1
order by good_name

注意看,gall這一行數據的累加的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章