hive 多行同时转列 lateral view explode 和 lateral view posexplode

最近在写一个需求过程中遇到一个多行同时转列的问题,感受到HQL的强大之处
实验数据即sql:

-- 实验数据
1 2.0,3.0,6.0 2.0,3.0,6.0
3 8.0,9 8,9
-- 建表
create table laterview(
    id int,
    event_list array<DOUBLE>,
    res_list array<DOUBLE>
)
row format delimited 
fields terminated by ' '
collection items terminated by ',';
load data local inpath '/root/data/hive_data/laterview.dat' into table laterview;
-- 使用 lateral view explode 能得到一行的行转列,当不能多行使用,否则出现笛卡尔积。
-- 这相当于通过id进行了全连接,因此我们需要在id相同的前提下,能再有一个字段进行辅助关联
select 
    id,
    event,
    res
from laterview
lateral view explode(event_list) t1 as event
lateral view explode(res_list) t1 as res;
-----
a.id    a.event b.res
1       2.0     2.0
1       2.0     3.0
1       2.0     6.0
1       3.0     2.0
1       3.0     3.0
1       3.0     6.0
1       6.0     2.0
1       6.0     3.0
1       6.0     6.0
3       8.0     8.0
3       8.0     9.0
3       9.0     8.0
3       9.0     9.0


-- 使用lateral view posexplode,会生成一个pos列,这是一个排序的列,具体如下:
select 
    pos1,
    pos2,
    id,
    event,
    res
from laterview
lateral view posexplode(event_list) t1 as pos1,event
lateral view posexplode(res_list) t2 as pos2,res
where pos1=pos2;

-----
id      event   res
1       2.0     2.0
1       3.0     3.0
1       6.0     6.0
3       8.0     8.0
3       9.0     9.0

-- 如上结果所示,达到了多行同时转列的目的
image.png
image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容