2016年4月5日星期二

Hive中使用first_value和max等窗口函数

遇到一个需求,统计不同的phone_device_id最近的event_timestamp的status值出现的次数,原始数据距离(phone_device_id, status, event_timestamp):
a 0 10
a 1 20
b 1 10
c 1 20
b 0 30
c 0 10
需要的结果:
0 1
1 2
因为a最新的状态是1,b最新的状态是0,c最新的状态是1,所以0总共有1个,1总共有2个。

可以使用以下语句实现,主要是max() over()和first_value() over():
select get_json_object(s2.first_value_window_1, '$.status'), count(distinct(phone_device_id)) from (select phone_device_id, max(event_timestamp) over (partition by phone_device_id), first_value(properties) over (partition by phone_device_id order by event_timestamp desc) from watch_upload_info where event_date = '2016-04-04' and get_json_object(properties, '$.action') = 'aw_status' and event = 'click') s2 group by get_json_object(s2.first_value_window_1, '$.status');

还可以使用另外一个方法:
先根据phone_device_id来分组取出event_timestamp最大的那条记录存到一张临时表中,然后和原表进行join得到status字段,然后再分组。

没有评论:

发表评论