以下面的例子做行列转换
创建表t_score
Student_id | Student_name | Course_name | Score |
1 | 小明 | 语文 | 92 |
1 | 小明 | 数学 | 84 |
1 | 小明 | 英语 | 73 |
2 | 小红 | 语文 | 86 |
2 | 小红 | 数学 | 72 |
2 | 小红 | 英语 | 63 |
create table t_score(
student_id int(11) not null comment '学号',
student_name varchar(20) not null comment '学生名字',
course_name varchar(20) not null comment '课程名称',
score int(11) not null comment '成绩'
)engine=innodb default charset=utf8 comment '学生成绩表';
insert into t_score values
(1, '小明', '语文', 92),
(1, '小明', '数学', 84),
(1, '小明', '英语', 73),
(2, '小红', '语文', 86),
(2, '小红', '数学', 72),
(2, '小红', '英语', 63);
编写sql,查询结果如下:
Student_id | Student_name | 语文 | 数学 | 英语 |
1 | 小明 | 92 | 84 | 73 |
2 | 小红 | 86 | 72 | 63 |
SELECT
max(student_id) student_id,
student_name,
max(
CASE course_name
WHEN '语文' THEN
score
END
) '语文',
max(
CASE course_name
WHEN '数学' THEN
score
END
) '数学',
max(
CASE course_name
WHEN '英语' THEN
score
END
) '英语'
FROM
t_score
GROUP BY
student_name;