mysql中使用case when 和sum()配合统计

先知道一下常用语法:
sum(case 属性名 when 属性值1 then 1 else 0 end),意思就是某个属性下为属性值1就加1个数量,否则就作0统计

题目:

查询各科成绩最高分、最低分和平均分,以如下形式显示:课程 ID,课程 name,最高分,最低分,平均分,及格率,中等率,优良率,优秀率(及格为>=60,中等为:70-80,优良为:80-90,优秀为:>=90)。
要求输出课程号和选修人数,查询结果按人数降序排列,若人数相同,按课程号升序排列
 

select c.cid as 课程号, c.cname as 课程名称, count(*) as 选修人数,
    max(score) as 最高分, min(score) as 最低分, avg(score) as 平均分,
    sum(case when score >= 60 then 1 else 0 end)/count(*) as 及格率,
    sum(case when score >= 70 and score < 80 then 1 else 0 end)/count(*) as 中等率,
    sum(case when score >= 80 and score < 90 then 1 else 0 end)/count(*) as 优良率,
    sum(case when score >= 90 then 1 else 0 end)/count(*) as 优秀率
from sc, course c
where c.cid = sc.cid
group by c.cid
order by count(*) desc, c.cid asc

答: 这里的case when使用当达到条件时就给1,外面有个sum来加起来,如果外面没有sum没法计数,这样就可以获取总人数.

猜你喜欢

转载自blog.csdn.net/weixin_44282540/article/details/106874155