hive 中的多列进行group by查询方法

 在工作中用hive进行数据统计的时候,遇到一个用group by 进行查询的问题,需要统计的字段为

gid,sid,user,roleid,time,status,map_id,num

其中time字段为时间戳形式的,统计要求为将各个字段按照每个小时的num总数进行统计

开始的时候写的hive SQL为

select gid,sid,user,roleid,time,status,map_id,sum(num) from test group by gid,sid,user,roleid,from_unixtime(time,'yyyyMMddHHmmss'),9,2),time,status,map_id;

在hive中执行后发现结果不对,hive是按照time字段进行的group by,于是将group by中的time字段去掉

select gid,sid,user,roleid,time,status,map_id,sum(num) from test group by gid,sid,user,roleid,from_unixtime(time,'yyyyMMddHHmmss'),9,2),status,map_id;

hive返回错误FAILED: Error in semantic analysis: Line 1:27 Expression not in GROUP BY key time

如果修改sql为

select gid,sid,user,roleid,from_unixtime(time,'yyyyMMddHHmmss'),9,2),status,map_id,sum(num) from test group by gid,sid,user,roleid,from_unixtime(time,'yyyyMMddHHmmss'),9,2),status,map_id;

可以按照小时进行汇总统计,可是字段time不是想要显示的结果,最后经过google查到方法

select gid,sid,user,roleid,collect_set(time)[0],status,map_id,sum(num) from test  group by gid,sid,user,roleid,substr(from_unixtime(time,'yyyyMMddHHmmss'),9,2),status,map_id;

 

参考网址http://stackoverflow.com/questions/5746687/hive-expression-not-in-group-by-key

看来对hive的udf函数还是掌握的不够,需要多学习

本文出自 “东杰书屋” 博客,转载请与作者联系!

你可能感兴趣的:(hive,by,group)