本文首發(fā)于:大數(shù)據(jù)每日嗶嗶-Hive 分析函數(shù)
Hive 分析函數(shù)
應用場景
(1)用于分區(qū)排序<br />(2)Top N<br />(3)層次查詢
<a name="kFMpa"></a>
常用分析函數(shù)
| 分析函數(shù) | 描述 |
|---|---|
| RANK | 返回數(shù)據(jù)項在分區(qū)中的排名。排名值序列可能會有間隔 |
| DENSE_RANK | 返回數(shù)據(jù)項在分區(qū)中的排名。排名值序列是連續(xù)的,沒有間隔 |
| PERCENT_RANK | 計算當前行的百分比排名:(x - 1)/(窗口分區(qū)中的行數(shù) - 1) |
| CUME_DIST | 統(tǒng)計小于或等于當前值的行數(shù)占總行數(shù)的比例:<br />x/分區(qū)行數(shù) |
| ROW_NUMBER | 確認分區(qū)中當前行的序號 |
| NTILE | 將每個分區(qū)的行盡可能均勻地劃分為指定數(shù)量的分組 |
語法:analytics_functions over() clause
準備了一個表,用于測試:
create table test.gid_pv(
gid string comment '商品ID'
,dt string comment '日期'
,pv string comment '訪問次數(shù)'
) comment '商品訪問次數(shù)'
row format delimited
fields terminated by ','
collection items terminated by '\n'
stored as textfile
;
數(shù)據(jù)如下:
0006D2BC-4DF9-4C0B-83AD-0183789E78D4 2020-01-10 1
0006D2BC-4DF9-4C0B-83AD-0183789E78D4 2020-01-11 5
0006D2BC-4DF9-4C0B-83AD-0183789E78D4 2020-01-12 7
0006D2BC-4DF9-4C0B-83AD-0183789E78D4 2020-01-13 3
0006D2BC-4DF9-4C0B-83AD-0183789E78D4 2020-01-14 2
0006D2BC-4DF9-4C0B-83AD-0183789E78D4 2020-01-15 4
0006D2BC-4DF9-4C0B-83AD-0183789E78D4 2020-01-16 4
993BD7AD-3B62-BA0C-15AE-A14B85921889 2020-01-10 2
993BD7AD-3B62-BA0C-15AE-A14B85921889 2020-01-11 9
993BD7AD-3B62-BA0C-15AE-A14B85921889 2020-01-12 3
993BD7AD-3B62-BA0C-15AE-A14B85921889 2020-01-13 1
993BD7AD-3B62-BA0C-15AE-A14B85921889 2020-01-14 1
993BD7AD-3B62-BA0C-15AE-A14B85921889 2020-01-15 8
993BD7AD-3B62-BA0C-15AE-A14B85921889 2020-01-16 2
RANK函數(shù)會返回數(shù)據(jù)項在分區(qū)中的排名。OVER子句中的ORDER BY語句來確定根據(jù)哪個值進行排名。如果多行中的排序值相同,則會有相同的排名。如果有排名相同的情況下,則會在名次中留下空位。例如,如果兩行排名為3,則下一個排名為5。DENSE_RANK()不會出現(xiàn)這種情況,具體可以對比一下
select
gid
,dt
,pv
,rank() over (partition by gid order by pv desc) as pre_total_pv_rank
,dense_rank() over (partition by gid order by pv desc) as pre_total_pv_dense_rank
from test.gid_pv
order by
gid
,dt
;
image.png
image.png
上面的兩個是排序函數(shù),如果只想給當前行編個號呢?
select
gid
,dt
,pv
,row_number() over (partition by gid order by pv) as pre_total_pv_row_number
from test.gid_pv
order by
gid
,dt
;
image.png
CUME_DIST函數(shù)計算分區(qū)中當前行的相對排名:(前面的行數(shù))/(分區(qū)中的總行數(shù))<br />如果有相等值的行(取決于OVER子句中的order by):(前面的行數(shù)+相等值行數(shù))/(分區(qū)中的總行數(shù))
一般默認升序即可。
select
gid
,dt
,pv
-- (前面的行數(shù))/(分區(qū)中的總行數(shù)),如果有相等值的行:(前面的行數(shù)+相等值行數(shù))/(分區(qū)中的總行數(shù))
,cume_dist() over (partition by gid order by pv) as pre_total_pv_cume_dist
from test.gid_pv
order by
gid
,dt
;
結(jié)果數(shù)據(jù):<br />image.png
image.png
select
gid
,dt
,pv
,ntile(4) over (partition by gid order by pv) as pre_total_pv_ntile
from test.gid_pv
order by
gid
,dt
;
結(jié)果如下:<br />
image.png
image.png
<a name="6TErV"></a>
參考
https://blog.csdn.net/SunnyYoona/article/details/56488568<br />https://cwiki.apache.org/confluence/display/Hive/LanguageManual+WindowingAndAnalytics<br />https://jordenbruce.com/2019/12/09/hql-function-analytic/