一、题目
有学生各学科分数表,记录了学生的各科分数,请按照学生粒度,生成两列数据分别为学科和分数,要求学科内的顺序与分数顺序一致。
数据样例:

二、思路
这是一个行转列的典型问题,目标是将张三的三条记录合并为一条。根据题意最终的数据是这个样子:张三 语文,数学,英语 95,80,82。
要处理这样的问题,首先按照一定的顺序对数据进行排序,然后将一个学生的多条记录整合为一条。涉及知识点:collect_list、concat_ws
三、解答
select
student,
concat_ws(',', collect_list(subject)) subject_list,
concat_ws(',', collect_list(cast(score as string))) score_list
from (
select
student,
subject,
score
from student_score_l2c
order by student,
score
) t11
group by student结果:
数据
# 建表
--建表语句
create table if not exists student_score_l2c(
student string,
subject string,
score bigint
)
stored as parquet
;
--插入数据
insert into table student_score_l2c(student, subject, score) values
('张三', '语文', 95),
('张三', '数学', 80),
('张三', '英语', 82),
('李四', '语文', 90),
('李四', '数学', 90),
('李四', '英语', 93),
('王五', '语文', 88),
('王五', '数学', 92),
('王五', '英语', 88),
('赵六', '语文', 77),
('赵六', '数学', 84),
('赵六', '英语', 68);注:题目获取自网络
评论