玩转大数据大数据

数据分析之hive开窗函数(一)

2021-12-17  本文已影响0人  坨坨的大数据

温馨提示 : 本文非小白科普文

开窗函数简介

MYSQL 暂时还未对开窗函数给予支持。

测试数据

图片

01、count 开窗函数

select username,product,user_type,price,

以符合条件的所有行作为窗口
count(price) over() as count1,

以按user_type分组的所有行作为窗口
count(price) over(partition by user_type)as count2,

以按user_type分组、按price排序的所有行作为窗口
count(price) over(partition by user_type order by price) as count3,

以按user_type分组、按price排序、按当前行+往前1行+往后2行的行作为窗口
count(price) over(partition by user_type order by price rows between 1 preceding and 2 following) as count4

from test;

图片

02、sum 开窗函数

select username,product,user_type,price,

以符合条件的所有行作为窗口
sum(price) over() as sum1,

以按user_type分组的所有行作为窗口
sum(price) over(partition by user_type) as sum2,

以按user_type分组、按price排序后、按到当前行(含当前行)的所有行作为窗口
sum(price) over(partition by user_type order by price) as sum3,

以按user_type分组、按price排序后、按当前行+往前1行+往后2行的行作为窗口
sum(price) over(partition by user_type order by price rows between 1 preceding and 2 following) as sum4

from test;


图片

03、min 开窗函数

select username,product,user_type,price,

以符合条件的所有行作为窗口
min(price) over() as min1,

以按classId分组的所有行作为窗口
min(price) over(partition by classId) as min2,

以按classId分组、按price排序后、按到当前行(含当前行)的所有行作为窗口
min(price) over(partition by classId order by price) as min3,

以按classId分组、按price排序后、按当前行+往前1行+往后2行的行作为窗口
min(price) over(partition by classId order by price rows between 1 preceding and 2 following) as min4

from test;

图片

04、max 开窗函数

select username,product,user_type,price,

以符合条件的所有行作为窗口
max(price) over() as max1,

以按classId分组的所有行作为窗口
max(price) over(partition by classId) as max2,

以按classId分组、按price排序后、按到当前行(含当前行)的所有行作为窗口
max(price) over(partition by classId order by price) as max3,

以按classId分组、按price排序后、按当前行+往前1行+往后2行的行作为窗口
max(price) over(partition by classId order by price rows between 1 preceding and 2 following) as max4

from test;


图片

05、avg 开窗函数

select username,product,user_type,price,

以符合条件的所有行作为窗口
avg(price) over() as avg1,

以按classId分组的所有行作为窗口
avg(price) over(partition by classId) as avg2,

以按classId分组、按price排序后、按到当前行(含当前行)的所有行作为窗口
avg(price) over(partition by classId order by price) as avg3,

以按classId分组、按price排序后、按当前行+往前1行+往后2行的行作为窗口
avg(price) over(partition by classId order by price rows between 1 preceding and 2 following) as avg4

from test;


图片

相关函数总结

注意:
如果不指定ROWS BETWEEN , 默认为从起点到当前行;

上一篇 下一篇

猜你喜欢

热点阅读