首页 > 编程知识 正文

大数据之HiveHive 开窗函数二,二本大数据

时间:2023-05-05 00:58:41 阅读:245492 作者:2120

目录 前言1.last_value开窗函数2.lag开窗函数3.lead开窗函数4.cume_dist开窗函数

前言

书接上回,上回重点讲了聚合函数之count开窗函数,first_value开窗函数;
言归正传,这次我们重点讲解lag开窗函数和cume_dist开窗函数;

1.last_value开窗函数

语义:返回分区中最后一个值(某一列属性的最后一个值)
同first-value开窗函数;

2.lag开窗函数


语义:lag(col,n,default) 用于统计窗口内往上第n个值。
col:列名
n:往上第n行
default:往上第n行为NULL时候,取默认值,不指定则取NULL

-- lag 开窗函数select studentId,math,departmentId,classId, --窗口内 往上取第二个 取不到时赋默认值60lag(math,2,60) over(partition by classId order by math) as lag1, --窗口内 往上取第二个 取不到时赋默认值NULLlag(math,2) over(partition by classId order by math) as lag2from student_scores where departmentId='department1';结果studentid math departmentid classid lag1 lag2111 69 department1 class1 60 NULL113 74 department1 class1 60 NULL112 80 department1 class1 69 69115 93 department1 class1 74 74114 94 department1 class1 80 80124 70 department1 class2 60 NULL121 74 department1 class2 60 NULL123 78 department1 class2 70 70122 86 department1 class2 74 74结果解释: 第3行 lag1:窗口内(69 74 80) 当前行80 向上取第二个值为69 倒数第3行 lag2:窗口内(70 74) 当前行74 向上取第二个值为NULL 3.lead开窗函数

语义:lead(col,n,default) 用于统计窗口内往下第n个值。
col:列名
n:往下第n行
default:往下第n行为NULL时候,取默认值,不指定则取NULL
同lag开窗函数

4.cume_dist开窗函数


语义:计算某个窗口或分区中某个值的累积分布。假定升序排序,则使用以下公式确定累积分布:
小于等于当前值x的行数 / 窗口或partition分区内的总行数。其中,x 等于 order by 子句中指定的列的当前行中的值。
应用场景:统计小于等于当前分数的人数占总人数的比例

-- cume_dist 开窗函数select studentId,math,departmentId,classId,-- 统计小于等于当前分数的人数占总人数的比例round(cume_dist() over(order by math),2) cume_dist1-- 统计大于等于当前分数的人数占总人数的比例round(cume_dist() over(order by math desc),2) cume_dist2,-- 统计分区内小于等于当前分数的人数占总人数的比例round(cume_dist() over(partition by classId order by math),2) cume_dist3from student_scores where departmentId='department1';结果studentid math departmentid classid cume_dist1 cume_dist2 cume_dist3111 69 department1 class1 0.11 1.0 0.2113 74 department1 class1 0.440.78 0.4112 80 department1 class1 0.67 0.44 0.6115 93 department1 class1 0.89 0.22 0.8114 94 department1 class1 1.0 0.11 1.0124 70 department1 class2 0.22 0.89 0.25121 74 department1 class2 0.44 0.78 0.5123 78 department1 class2 0.56 0.56 0.75122 86 department1 class2 0.78 0.33 1.0结果解释: 第三行: cume_dist1=小于等于80的人数为6/总人数9=0.6666666666666666 cume_dist2=大于等于80的人数为4/总人数9=0.4444444444444444 cume_dist3=分区内小于等于80的人数为3/分区内总人数5=0.6

参考:https://blog.csdn.net/wangpei1949/article/details/81437574

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。