Hive之行转列/列转行

1、行转列

场景:在hive表中,一个用户会有多个人群标签,List格式(逗号分隔如要转成List),有时我们需要统计一个人群标签下有少用户,这是就需要使用行转列了

例如,user_crowd_info有如下数据

1
2
3
4
visit_id    crowds
abc [100,101,102]
def [100,101]
abe [101,105]

可以使用的函数

1
2
3
4
5
6
7
8
9
10
select explode(crowds) as crowd from user_crowd_info;

结果:
100
101
102
100
101
101
105

这样执行的结果只有crowd, 但是我们需要完整的信息,使用select visit_id, explode(crowds) as crowd from user_crowd_info;是不对的,会报错UDTF's are not supported outside the SELECT clause, nor nested in expressions

所以我们需要这样做:

1
2
select visit_id,crowd
from user_crowd_info t lateral view explode(t.crowds) adtable as crowd;

2、列转行

使用concat_ws函数即可

1
select visit_id,concat_ws(,crowd) from user_crowd_info group by visit_id;