用一句SQL语句查询成绩优良中差的人数

遇到一个基础的笔试题,有关sql查询的,感觉很有趣,正好复习下相关的知识。

成绩表如下:



1.查询出每门课程的成绩都大于80的学生姓名

-- 通过分组聚合函数,最小的分数都大于80
SELECT sname
FROM test.Score
group by sname 
having min(snum)>80
;
-- 通过all 关键字,all要放到比较的右侧
select sname
from test.Score t1
where 80<all(select snum from test.Score t2 where t2.sname=t1.sname);
-- 逆向思维
select sname
from test.Score t1
where not exists(select 1 from test.Score t2 where t2.sname=t1.sname and t2.snum<=80);

2.用一句SQL语句查询成绩优良中差的人数

规定:
<60 不合格 
>=60 <70 中
>=70 <90  良
>=90 优

SELECT 
sum(case when snum<60 then 1 else 0 end) AS 不合格,
sum(case when snum>=60 AND snum<70 then 1 else 0 end) AS 中,
sum(case when snum>=70 AND snum< 90 then 1 else 0 end) AS 良,
sum(case when snum>=90 then 1 else 0 end) AS 优
FROM test.Score;


3. 按姓名分组,查看每个学生的优良中差统计

SELECT sname, count(snum) 总数,
sum(case when snum<60 then 1 else 0 end) AS 不合格,
sum(case when snum>=60 AND snum<70 then 1 else 0 end) AS 中,
sum(case when snum>=70 AND snum< 90 then 1 else 0 end) AS 良,
sum(case when snum>=90 then 1 else 0 end) AS 优
FROM test.Score
group by sname
;

4. 按科目分组,查看优良中差

SELECT clazz, count(snum) 总数,
sum(case when snum<60 then 1 else 0 end) AS 不合格,
sum(case when snum>=60 AND snum<70 then 1 else 0 end) AS 中,
sum(case when snum>=70 AND snum< 90 then 1 else 0 end) AS 良,
sum(case when snum>=90 then 1 else 0 end) AS 优
FROM test.Score
group by clazz
;



点击下载源码



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值