有一张学生成绩表sc(sno 学号,class 课程,score 成绩),示例如下:
请问哪个语句可以查询出每个学生的英语、数学的成绩(行转列,一个学生输出一行记录,比如输出[1, 89, 90])?
select sno,class,score from sc where class in('english','math')
select sno,
if(class='english',score,0),
if(class='math',score,0)
from sc
where class in('english','math')
select sno,
case when class='english' then score else 0 end ,
case when class='math' then score else 0 end
from sc
where class in('english','math')
select sno,
sum(if(class='english',score,0)) as english,
sum( if(class='math',score,0) ) as math
from sc
where class in('english','math')
group by sno
错误答案C:没达到行转列的目的 select sno, case when class='english' then score else 0 end , case when class='math' then score else 0 end from sc where class in('english','math') 结果:一个学生最终会出现两条记录(英语和数学),每条记录都是满足当前class条件的那门课程成绩正常,其余课程成绩为0 张三 80 0 张三 0 79 王五 60 0 王五 0 88 修改为: select sno, sum(case when class='english' then score else 0 end ) as english, sum(case when class='math' then score else 0 end) as math from sc where class in('english','math') group by sno; 正确答案D: select sno, sum(if(class='english',score,0)) as english, sum( if(class='math',score,0) ) as math from sc where class in('english','math') group by sno 如果科目为English为真,English成绩+score,否则+0!!! 结果: 张三 80 79 王五 60 88