explode和inline函数可以将单列扩展成多列或者多行。
1.explode将单列扩展成多行
select explode(subordinates) from employees;
explode的参数可以是array还可以是map,如果是map,将生成2个字段,一个是map的键,字段名为key,一个是map的值,字段的名为:value,如下:
select explode(deductions) from employees ;
explode的限制,如下sql不支持:
- 不能和其他字段一起使用
select name,explode(subordinates) from employees;
- 不支持函数嵌套
select explode(explode(subordinates)) from employees
- 不能和group by、sort by 和cluster by一起使用
select explode(subordinates)
from employees
group by explode(subordinates)
2.inline
inline的参数形式:inline(ARRAY<STRUCT[,STRUCT]>)
inline一般结合lateral view使用
select t1.col1 as name,t1.col2 as sub1
from employees
lateral view inline(array(struct(name,subordinates[0]))) t1
inline 嵌套多个struct,
select t1.col1 as name,t1.col2 as sub
from employees
lateral view inline(array(struct(name,subordinates[0]),
struct(name,subordinates[1]))) t1
where t1.col2 is not null
还可以给inline的字段取别名:
select t1.name,t1.sub
from employees
lateral view inline(array(struct(name,subordinates[0]),
struct(name,subordinates[1]))) t1 as name,sub
where t1.sub is not null