多行转一行(collect_set(col)):
- 原始数据
Paste_Image.png
hive>create table tmp_wlt_test1 as select id,collect_set(name) as name_set from tmp_wlt_test group by id;
Paste_Image.png
hive> select id,name_set[1] from tmp_wlt_test1;
Paste_Image.png
注:可以利用concat_ws将array<string>类型的数据转化为string类型,可以利用split将string转为array<string>, array的起始数字为0
hive> create table tmp_wlt_test2 as select id,concat_ws(',',collect_set(name)) as name_set from tmp_wlt_test group by id;
Paste_Image.png
Paste_Image.png
一行转多行(explode(ARRAY)):
Paste_Image.png
里面name_set是一个array<string>类型的数据,这里报错的原因是因为有id字段,当select中只有name_set一列数据时,可以跑通
hive> create table tmp_wlt_test3 as select explode(name_set) as name from tmp_wlt_test1;
Paste_Image.png
一行转多行(explode(ARRAY), Lateral View ):
lateral view 可以解决explode无法添加额外的select列的问题。
Lateral view 其实就是用来和像类似explode这种UDTF函数联用的。lateral view 会将UDTF生成的结果放到一个虚拟表中,然后这个虚拟表会和输入行即每个game_id进行join 来达到连接UDTF外的select字段的目的。
lateral view用法:Lateral View用法 与 Hive UDTF explode - OopsOutOfMemory盛利的博客 - 博客频道 - CSDN.NET
上述问题可以用如下语句解决:
hive> create table tmp_wlt_test3 as select a.id,b.name from tmp_wlt_test1 a lateral view explode(name_set) b as name; -- lateral view explode(name_set) 临时表名 as 列名
Paste_Image.png