pb9数据窗口中显示行数据与当前行区别_Hive的窗口函数
聚合函數(如sum()、avg()、max()等等)是針對定義的行集(組)執行聚集,每組只返回一個值。
窗口函數也是針對定義的行集(組)執行聚集,可為每組返回多個值。如既要顯示聚集前的數據,又要顯示聚集后的數據。
窗口查詢有兩個步驟:將記錄分割成多個分區,然后在各個分區上調用窗口函數。
語法:主要是over( PARTITION BY (根據某條件分組,形成一個小組)….ORDER BY(再組內進行排序) …. )
over:
over (order by col1) --按照 col1 排序, 沒分區范圍就是整個表over (partition by col1) --按照 col1 分區 over (partition by col1 order by col2) -- 按照 col1 分區,按照 col2 排序--帶有窗口范圍over (partition by col1 order by col2 ROWS 窗口范圍) -- 在窗口范圍內,按照 col1 分區,按照 col2 排序實例:
-- 按照age排序,每階段的age數據進行統計求和
select id,age,name, count() over(order by age) from wt1;結果:
-- 窗口范圍是表下按照age進行分區
-- 在分區里面,再按照age進行排序
select id,age,name, count() over(partition by age order by age) from wt1;-- 窗口范圍是表下按照age進行分區
-- 在分區里面,再按照id進行降序排序
select id,age,name, count() over(partition by age order by age) from wt1;序列函數
row_number:會對所有數值,輸出不同的序號,序號唯一且連續,如:1、2、3、4、5。
rank:會對相同數值,輸出相同的序號,而且下一個序號間斷,如:1、1、3、3、5。
dense_rank:會對相同數值,輸出相同的序號,但下一個序號不間斷,如:1、1、2、2、3。
ROW_NUMBER()
row_number() OVER (PARTITION BY COL1 ORDER BY COL2)表示根據COL1分組,在分組內部根據 COL2排序,而此函數計算的值就表示每組內部排序后的順序編號(組內連續的唯一的)。
表數據:
-- rn_id 按照性別分組,按照id排序
select id,sex,name, row_number() over(partition by sex order by id desc) from student;--查詢student表中按照sex分組,取每組的最小id的記錄
select a.* from (select sex,age,id, row_number() over(partition by sex order by id) as rn from student) a where a.rn = 1;over中partition by和distribute by區別:
1)partition by [key..] order by [key..]只能在窗口函數中使用,而distribute by [key...] sort by [key...]在窗口函數和select中都可以使用。
2)窗口函數中兩者是沒有區別的
3)where后面不能用partition by
Window 函數:
ROWS窗口函數中的行選擇器 rows between [n|unbounded preceding]|[n|unbounded following]|[current row] and [n|unbounded preceding]|[n|unbounded following]|[current row]
參數解釋:
n行數
unbounded不限行數
preceding在前N行
following在后N行
current row當前行
應用場景:
1)查詢當月銷售額和近三個月的銷售額
2)查詢當月銷售額和今年年初到當月的銷售額
表數據:
實例:
-- 查詢當月銷售額和近三個月的銷售額
SELECT y, m, sales, sum(sales) OVER(PARTITION BY y ROWS between unbounded preceding and current row) AS s2 FROM sale_table;總結
以上是生活随笔為你收集整理的pb9数据窗口中显示行数据与当前行区别_Hive的窗口函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 欠信用卡钱会坐牢吗?抓人不是吓唬人的
- 下一篇: 开发物体识别桌、_想用人工智能实现安全风