hive 实现多行转一行处理方法

最近公司在做客户端阅历数据分析,服务器端同事需要计算每个用户的读书分类,读了多少本书,读过多少本书,总时长,总分,数据量非常大,服务器同事那边单机处理一次需要10个小时,后来我拿来我们这边做,分布式计算总比单机计算快吧,所以分享一下:

1.需要统计每个用户的书籍分类

sql:

select  us.user_name,us.bid,b.classname  from  book_class  
b  join user_all_books_times us on (us.bid=b.bid)

 首先统计出来用户读书的分类

2.上面sql查询出来有三个字段需要转化为两个字段

user_name       classtypeNum 

张三                   1000003:56----分类10000003 有56本

sql:

hive -e "create table  user_book_class  as   select  
user_name,concat(classname,':',num) as cl from  (select
 user_name,classname,sum(1) as num from (select  
us.user_name,us.bid,b.classname  from  book_class  b  
join user_all_books_times_sup us on (us.bid=b.bid)) f 
 group by user_name,classname) f1"

 3.一个用户对应很多个分类,所以一个用户会有很多行记录,那么最后转化为一行

user_name      classtypesum

张三                  100004:56,100004:47,,,,,,,,,,

sql:

select user_name, concat_ws(',', collect_set(cl) as 
classtype  from  user_book_class where cl is not null 
and cl !=''  group by  user_name;

 最后满足需求,20分钟搞定,也可以自己写一个UTAF来实现。

猜你喜欢

转载自wrn19851021-163-com.iteye.com/blog/1968176