hive 多行同時轉列 lateral view explode 和 lateral view posexplode

最近在寫一個需求過程中遇到一個多行同時轉列的問題,感受到HQL的強大之處
實驗數(shù)據(jù)即sql:

-- 實驗數(shù)據(jù)
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 能得到一行的行轉列,當不能多行使用,否則出現(xiàn)笛卡爾積。
-- 這相當于通過id進行了全連接,因此我們需要在id相同的前提下,能再有一個字段進行輔助關聯(lián)
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
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容