实现多列转多行
1、创建测试数据
create table if not exists wedw_tmp.test_explode_df(
id STRING,
time STRING
)
row format delimited fields terminated by '-'
lines terminated by '\n';
insert overwrite table wedw_tmp.test_explode_df
select
'a,b,c,d' as id,
'2:00,3:00,4:00,5:00' as `time`
union all
select
'e,b,c,d' as id,
'1:20,2:00,3:30,4:40' as `time`
2、现在先进行一列转多行的操作,这里就用到了explode()函数,将第二列time中的数据用逗号切分并成为第三列,操作如下
select id,time,single_time
from wedw_tmp.test_explode_df lateral view explode(split(time,',')) t as single_time
可以看出上面的代码实现了对第二列的多行转换,现在如果想实现对两列听同事进行多行转换,那么用explode()函数就不能实现了,但可以用posexplode()函数,因为该函数可以将index和数据都取出来,使用两次posexplode并令两次取到的index相等就行了。
3、使用一次posexplode()函数效果如下:
select id,time,single_id_index,single_id from wedw_tmp.test_explode_df lateral view posexplode(split(id,',')) t as single_id_index, single_id;
2、使用两次posexplode()函数实现多列转多行
select id,time,single_id_index ,single_time_index,single_id,single_time from wedw_tmp.test_explode_df
lateral view posexplode(split(id,',')) t as single_id_index, single_id
lateral view posexplode(split(time,',')) t as single_time_index, single_time
where single_id_index = single_time_index;
结论:
explode()仅可以实现一列转行
posexplode()可实现多列转行