目录
一:行转列
1:lateral view---行转列
lateral view用于和split, explode(展开)等UDTF一起使用,它能够将一行数据拆成多行数据,在此基础上可以对拆分后的数据进行聚合。lateral view首先为原始表的每行调用UDTF,UTDF会把一行拆分成一或者多行,lateral view再把结果组合,产生一个支持别名表的虚拟表。
一列:直接上面
select 字段,新字段 from 表名 lateral view explode(score) s as 新字段;
多列
select 字段,新字段... from 表名 lateral view explode(score...等字段) s as 新字段....;
s是虚拟的表的名称
2:explode函数
参数仅接受array和map类型,不支持两个一起用。所以lateral view可以解决。
3:例子
(1:当需要转列的数据是数组时、
创建表
create table testArray2(
name string,
weight array<string>
)row format delimited
fields terminated by '\t'
COLLECTION ITEMS terminated by ',';
(2:当需要转的是map时(或者其他多个字段数据时)
select key from (select explode(map('key1',1,'key2',2,'key3',3)) as (key,value)) t;
二:列转行
1:概念
collect_list collect_map转成list或者map列转行
select 字段 collect_list(字段) from 表名 group by 字段;
2:例子
建表
create table testLieToLine(
name string,
col1 int
)row format delimited
fields terminated by '\t';
数据