@羲凡——只为了更好的活着
Hive 行转列 explode和inline(lateral view)
任何一个数据库都会涉及到行转列的问题,也同时会有相应的方法,比如mysql中的pivot。hive中使用的则是 lateral view explode 或者 lateral view inline
1.语法说明
a.lateral view explode
select source_column,new_column
from source_table
lateral view explode(source_column) new_table as new_column;
source_table:表示需要行转列的表
source_column:表示 source_table 中需要行转列的列
new_table:表示 lateral view explode 生成的新表名
new_column:表示 source_column 行转列后生成的新列名
b.lateral view inline
select source_column,new_column1,new_column2
from source_table
lateral view inline(source_column) new_table as new_column1,new_column2;
source_table:表示需要行转列的表
source_column:表示 source_table 中需要行转列的列
new_table:表示 lateral view explode 生成的新表名
new_column1:表示 source_column 的key行转列后生成的新列名
new_column2:表示 source_column 的value行转列后生成的新列名
2.创建表
CREATE TABLE `aarontest.table_array_struct_map`(
`id` int,
`name` string,
`attribute` array<struct<key:string,value:string>>)
ROW FORMAT delimited fields terminated by '\t'
COLLECTION ITEMS TERMINATED BY ','
MAP KEYS TERMINATED BY ':';
3.加载数据
load data local inpath "/hive/test" into table aarontest.table_array_struct_map;
查看导入结果
4.行转列(explode)
select name,c1.value from
table_array_struct_map
lateral view explode(attribute) t1 as c1
where c1.key="city";
5.行转列(inline)
select name,c2
from table_array_struct_map
lateral view inline(attribute) t1 as c1,c2
where c1="city";
===================================================================
@羲凡——只为了更好的活着
若对博客中有任何问题,欢迎留言交流