美文网首页
一行与多行转化

一行与多行转化

作者: Amyfeelily | 来源:发表于2017-07-06 17:12 被阅读0次

多行转一行(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

相关文章

网友评论

      本文标题:一行与多行转化

      本文链接:https://www.haomeiwen.com/subject/kszhhxtx.html