Hive--sql中的窗口函數


今天對Hive–sql中的窗口函數及常用的一些內容做一個簡單的總結。

1. 清楚sql的關鍵字順序和執行順序

關鍵字順序

select … from … where … group by … having … order by … limit …

執行順序

from where group by having select order by limit

group by 的底層是distinct

在使用group by時需要注意:select出來的必須列在groupby中,或者聚合函數中

2. 在Hive命令行中可以對函數功能進行查看

show  functions;     //查看自帶的所有的內置函數

desc function upper;  //查看具體的某個函數的用法

desc function extended upper; //帶有具體案例

3. 窗口函數

窗口函數大體可以分爲以下兩種

1.能夠作爲窗口函數的聚合函數(sum,avg,count,max,min)
2.rank( ),dense_rank( ),row_number( )等專用窗口函數。

row_number(): 沒有並列,相同名次順序排序

rank(): 有並列,相同名次空位(即類似於1 1 3)

dense_rank(): 有並列,相同名次不空位(即類似於1 1 2)

注意:窗口函數的別名位置是在over()子句之後。

<窗口函數> over ([partition by <列清單>]
                        order by <排序用列清單>)

窗口函數over()使得聚合函數count()可以在限定的窗口中進行聚合。窗口函數over()和group by 的最大區別,在於group by之後其餘列也必須按照此分區進行計算,而over()函數使得單個特徵可以進行分區

窗口大小的設定

默認窗口大小是從起始行到當前行
partition by …order by…rows between unbounded preceding and current row
窗口大小爲從起始行得到當前行。
partition by …order by… rows between 3 preceding and current row
窗口大小爲從當前行到之前三行
partition by …order by… rows between 3 preceding and 1 following
窗口大小爲當前行的前三行到之後的一行
partition by …order by… rows between 3 preceding and unbounded following
窗口大小爲當前行的前三行到之後的所有行

3.1 rank( ),dens_rank( ),row_number()

select product_name, product_type, sale_price,
       rank () over (partition by product_type
	                        order by sale_price) as ranking
from Product;

在這裏插入圖片描述
partition by 能夠設定排序的對象範圍,類似於group by語句,這裏就是以product_type劃分排序範圍。

order by能夠指定哪一列,何種順序進行排序。也可以通過asc,desc來指定升序降序。

窗口函數兼具分組和排序兩種功能。通過partition by分組後的記錄集合稱爲窗口。

然而partition by不是窗口函數所必須的,不限定時就是對所有數據進行排序。

select product_name, product_type, sale_price,
       rank () over (order by sale_price) as ranking
from Product;

在這裏插入圖片描述
1.rank函數:計算排序時,如果存在相同位次的記錄,則會跳過之後的位次。
2.dense_rank函數:同樣是計算排序,即使存在相同位次的記錄,也不會跳過之後的位次。
3.row_number函數:賦予唯一的連續位次。

select product_name, product_type, sale_price,
       rank () over (order by sale_price) as ranking,
	   dense_rank () over (order by sale_price) as dense_ranking,
	   row_number () over (order by sale_price) as row_num
from Product;

在這裏插入圖片描述
由於窗口函數無需參數,因此通常括號裏都是空的。
窗口函數的適用範圍:只能在select子句中使用。

3.2 sum( ),avg( )等

select product_id, product_name, sale_price,
       sum(sale_price) over (order by product_id) as current_sum
from Product;

在這裏插入圖片描述
以累計的方式進行計算。計算出商品編號小於自己的商品的銷售單價的合計值。

4. 參考

https://www.bilibili.com/video/av50213838/?p=15
https://mp.weixin.qq.com/s/PsY1mjLXmqTDp_py75jDHQ
https://blog.csdn.net/qq_37296285/article/details/90940591
https://blog.csdn.net/qq_41805514/article/details/81772182

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