1. 程式人生 > 其它 >hive表實現行轉列和列轉行

hive表實現行轉列和列轉行

技術標籤:Hivehive行轉列列轉行

hive錶行轉列和列轉行


t1

itemnum
A1,2,3,4
B2,5,1

行轉列(lateral view explode)

--使用側檢視lateral view explode進行行轉列
create table t3 as with r1 as (select item ,nums from t1  lateral view explode(split(num,",")) t as nums) select * from r1;

select * from t3;

+----------+----------+--+
| t3.item | t3.nums | +----------+----------+--+ | A | 1 | | A | 2 | | A | 3 | | A | 4 | | B | 2 | | B | 5 | | B | 1 | +----------+----------+--+

t3

itemnums
A1
A2
A3
A4
B2
B5
B1

列轉行(collect_list,concat_ws)

--使用collect_list和concat_ws進行列轉行
select item ,concat_ws(",",collect_list(nums)) as num from t3 group by item;

+-------+----------+--+
| item  |   num    |
+-------+----------+--+
| A     | 1,2,3,4  |
| B     | 2,5,1    |
+-------+----------+--+