有一张学生成绩表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 关于比D少一个group by 的B选项错误原因:
如果在你的 SQL 查询中没有使用 GROUP BY 子句,那么查询会产生不同的结果。具体来说,没有 GROUP BY 会导致整个表的数据作为一个整体进行汇总,而不是按每个学生编号(sno)分组进行聚合。
GROUP BY 的情况:考虑以下修改后的 SQL 语句:
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)进行分组。SUM() 聚合函数将会应用于整个表(满足 WHERE 条件的记录),并且数据库将计算所有记录的总和。 sno 列:由于不进行分组,返回的 sno 列的值不确定,因为 sno 没有在聚合函数中,数据库在执行查询时可能会选择表中的任意一行的 sno。 假设表 sc 的数据如下:
| sno | class | score |
|---|---|---|
| 101 | english | 85 |
| 101 | math | 90 |
| 102 | english | 75 |
| 102 | math | 88 |
| 103 | english | 92 |
执行没有 GROUP BY 的查询后,结果可能会是:
| sno | english | math |
|---|---|---|
| 101 | 252 | 178 |
english 列:SUM(IF(class = 'english', score, 0)) 将所有英语成绩(85 + 75 + 92 = 252)相加。 math 列:SUM(IF(class = 'math', score, 0)) 将所有数学成绩(90 + 88 = 178)相加。 sno 列:由于没有 GROUP BY,数据库会随机选择一个 sno 值来显示,通常是表中的第一个记录的 sno 值(在本例中为 101)。 GROUP BY,那么查询会将整个表的数据视为一个整体来进行汇总,而不会按照每个学生编号来分组。 sno 可能是不确定的,因为在没有分组的情况下,数据库可能会选择表中的任意一条记录的 sno 来显示。