hive窗口函数last_value的一个小坑

先说结论

last_value窗口函数默认窗口是从第一条到当前条


问题描述

项目中没有使用过last_value窗口函数,最近第一次使用,发现和想象的不太一样。
一开始感觉 last_value(字段) over(partition by 分组字段 order by 排序字段) 直接可以取到分组字段里面的排序最后一个,结果并不是这样,瞬间懵逼,就去测试了下。


测试demo准备

--建表
create table if not exists test.test_last_value
(
department int comment '部门',
name string comment '姓名',
salary int comment '薪资'
)
;
--插入字段
insert into test.test_last_value values
(1,"aa",100),
(1,"bb",200),
(1,"cc",50),
(2,"dd",300),
(2,"ee",200),
(2,"ff",100)
;
--查询
select
*
from test.test_last_value;

hive窗口函数last_value的一个小坑_第1张图片


测试结果分析

select
*
,last_value(salary) over(partition by department order by salary) last_salary1
,last_value(salary) over(partition by department order by salary rows between unbounded preceding and current row) last_salary2
,last_value(salary) over(partition by department order by salary rows between unbounded preceding and unbounded following) last_salary3
from test.test_last_value tb
;

hive窗口函数last_value的一个小坑_第2张图片

最终last_salary1和last_salary2结果是一样的,也就是说窗口函数last_value不加rows between时窗口是从第一条到当前条,等同于rows between unbounded preceding and current row

而想要得到last_salary3这个结果,使用rows between unbounded preceding and unbounded following或者rows between current row and unbounded following实现。

你可能感兴趣的:(hive,大数据,数据仓库)