Hive 行转列
将行转列,可以用lateral view + explode 列子: 原数据
id | fruit |
---|
11 | apple,peach | 12 | banana,peach |
转为
id | fruit |
---|
11 | apple | 11 | peach | 12 | banana | 12 | peach |
代码:
select id,fruit2 from table_name
lateral view explode(split(fruit,‘,’)) t2 as fruit2
若需加上限制条件,如加上指定日期date select id,fruit2 from table_name lateral view explode(split(frui,t‘,’))) t2 as fruit2 where date=‘2021-01-01’
如要在列转多行后在进行聚合统计 代码:
select count(id) as id_num,fruit2 from table_name
lateral view explode(split(frui,t‘,’))) t2 as fruit2
group by fruit2;
结果如下
id_num | fruit |
---|
1 | apple | 2 | peach | 1 | banana |
对多列转行,可以用多个lateral view语句: 一个FROM语句后可以跟多个lateral view语句,后面的lateral view语句能够引用它前面的所有表和列名。如
代码:
select id,fruit2,amount2 from table_name
lateral view explode(split(fruit,',')) t1 as fruit2
lateral view explode(split(amount,',')) t2 as amount2
代码注释:其中上述t1,t2 为虚拟表表名。
|