mysql sql语句:行转列问题

存在表score,记录学生的考试成绩,如下图所示:

                

现要求以 学生姓名,语文,数学,英语 这种格式显示学生成绩,如下图所示

                

具体步骤如下:

1、首先,使用case when函数输出单个课程的成绩

case when course='语文' then score end as 语文

case when course='数学' then score end as 数学

case when course='英语' then score end as 英语

sql语句:

select name ,case when course='语文' then score end as 语文,

case when course='数学' then score end as 数学,

case when course='英语' then score end as 英语  from score;

输出结果如下图所示:

                

2、使用group by 和sum,去掉NULL得出课程的成绩

sql语句:

select name ,sum(case when course='语文' then score end) as 语文,
sum(case when course='数学' then score end )as 数学,
sum(case when course='英语' then score end )as 英语
from score group by name;

输出结果如下图所示

                

就得出行转列的输出结果了

总结:在具体的生活场景中,使用学生姓名,课程1,课程2,课程3……的表结构是不太合理的,比如选修课,不可能每个学生都选一样的课程,这种结构会存在浪费存储空间的情况,比较好的做法就是一行表示一个学生的某个课程的成绩,再使用行转列方法输出想要的成绩结构。

原文地址:https://www.cnblogs.com/linjinfeng/p/9039476.html