行转列指的是将多行的数据拼接之后放到一列上
在 Hive 中想实现按某字段分组,对另外字段进行合并,可通过collect_list()或者collect_set()实现。
collect_set()函数与collect_list()函数:列转行专用函数,都是将分组中的某列转为一个数组返回。有时为了字段拼接效果,多和concat_ws()函数连用。
collect_set()与collect_list()的区别:
collect_list()函数 - - 不去重
collect_set()函数 - - 去重
数据 game1.txt
超级玛丽 卡通
超级玛丽 横版
超级玛丽 单人
魂斗罗 动作
魂斗罗 横版
中国象棋 棋类
中国象棋 智力
建表语句:
create table game1(name string, gametype string) row format delimited fields terminated by ' ';
加载数据:
load data local inpath '/game1.txt' into table game1;
行转列:
select name,concat_ws('/', collect_set(gametype)) from game1 group by name;
多个数据行转列
数据 student1.txt
1 1 wj
1 2 fj
1 1 lm
1 1 sl
1 2 zy
1 3 tom
1 4 jack
1 2 lucy
1 1 hdh
1 2 rose
1 3 ben
1 1 charle
1 3 wend
建表语句:
hive
create table student1(nianji int,banji int, name string) row format delimited fields terminated by ' ' ;
加载数据:
load data local inpath '/student1.txt' into table student1;
行转列:
select nianji,banji,concat_ws(',',collect_list(name)) from student1 group by nianji,banji;