创建test表结构如下:


#将数组中的每个元素拆分为单独的行,生成单列
select explode(student) from test;

#单列拆分
select class,e_student from test lateral view explode(student) table_a as e_student;

#单列拆分——编号引入posexplode
select class,id,e_student from test lateral view posexplode(student) table_a as id,e_student;

#单列拆分——通过编号+1来实现序号从1开始
select class,id+1 stuid,e_student from test lateral view posexplode(student) table_a as id,e_student;

#多列拆分——错误示范直接用exploded会产生笛卡尔积
select class,e_student,e_score from test lateral view explode(student) table_a as e_student lateral view explode(score) table_a as e_score;

#多列拆分——正确做法配合posexplode()
select class,e_student,e_score from test lateral view posexplode(student) table_a as stuid,e_student lateral view
posexplode(score) table_a as sid,e_score where stuid=sid;

#开窗按班级班内排名
select class,e_student,e_score,rank() over(partition by class order by e_score desc) rk from test lateral view posexplode(student) table_a as stuid,e_student lateral view
posexplode(score) table_a as sid,e_score where stuid=sid;

创建test2表结构如下:


#将映射的键值对拆分为两列,分别对应 key和value
select explode(score) as (course,e_score) from test2 where student='小A';

#将映射的键值对拆分
select student,course,e_score from test2 lateral view explode(score) table_a as course,e_score;

posexplode()能否对键值类(map)进行编号呢?
select student,id,course,e_score from test2 lateral view posexplode(score) table_a as id,course,e_score;

这个错误提示表明你在使用posexplode函数时没有提供数组类型的参数。posexplode函数用于将数组(array)类型的列拆分成多行,同时保留元素在数组中的位置索引。
2518

被折叠的 条评论
为什么被折叠?



