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

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

开窗函数简介

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;


图片

相关函数总结

  • over():指定分析函数工作的数据窗口大小,这个数据窗口大小可能会随着行的变化而变化
  • preceding n:往前n行数据
  • following n:往后n行数据
  • current row:当前行
  • unbounded :无界限(起点或终点)
  • unbounded preceding:表示从前面的起点
  • unbounded following:表示到后面的终点

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容