0
点赞
收藏
分享

微信扫一扫

数据分析 | MySQL45道练习题(28~36)

洲行 2022-02-03 阅读 52

28.查询所有学生的课程及分数情况(存在学生没成绩没选课的情况)
-- 【分析】给学生信息加上课程情况

select a.sid,a.sname,c.cname,b.score
from student a
left join sc b
on a.sid = b.sid 
left join course c
on b.cid = c.cid;

29.查询任何一门课程成绩在70分以上的姓名、课程名称和分数
-- 【分析】条件查询结果

-- 1、先找出成绩大于70分的成绩记录,这里面的sid就是要找的学生 
select sid
from sc
where score > 70;
-- 2、和学生表进行关联得到学生信息记录 
select b.sname,c.cname,a.score
from sc a
left join student b
on a.sid = b.sid
left join course c
on a.cid = c.cid
where a.score > 70;

30.查询不及格的课程 
-- 【分析】条件查询 

-- 1、筛选出小于60分的成绩记录 
select cid
from sc
where score < 60;
-- 2、去重得到cid,如果需要课程信息还可以和course表做关联 
select a.*
from course a
where a.cid in (select cid
from sc
where score < 60);

31.查询课程编号为01且课程成绩在80分以上的学生的学号和姓名 

select a.sid,a.sname,b.cid,b.score
from student a
inner join sc b
on a.sid = b.sid
where b.cid = '01' and b.score > 80;

32.求每门课程的学生人数 

select b.cname,b.cid,count(a.sid) as cons
from sc a
left join course b
on a.cid = b.cid
group by a.cid;

33.假设成绩不重复,查询选修[张三]老师所授课程的学生中,成绩最高的学生信息及成绩 
-- 【分析】条件筛选查询,只需要一个人

select *
from sc a
left join student b
on a.sid = b.sid
left join course c
on a.cid = c.cid
left join teacher d
on c.tid = d.tid
where d.tname = '张三'
order by a.score desc
limit 1;

34.假设成绩有重复,查询选修[张三]老师所授课程的学生中,成绩最高的学生信息及成绩 

select *
from
(select 
    a.*,
    case when @score=score then @rank 
        when @score:=score then @rank:=@rank + 1 end as rk
from
(select a.sid,a.score,b.sname,c.cid,d.tname
from sc a
left join student b
on a.sid = b.sid
left join course c
on a.cid = c.cid
left join teacher d
on c.tid = d.tid
where d.tname = '张三') a ,(select @score:=null,@rank:=0) t) s
where rk = 1;

35.查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩 
-- 【分析】条件关联筛选 

select a.sid,a.cid,a.score
from sc a 
inner join sc b
on a.sid = b.sid
where a.cid != b.cid and a.score = b.score
group by a.cid,a.sid;

36.查询每门科目成绩最好的前两名 
-- 【分析】用户变量排序 

select
    sid,cid,score,rk
from
    (select 
    sc.*,
    @rank:=if(@c_cid=cid,if(@sco=score,@rank,@rank+1),1) as rk,
    @sco:=score,
    @c_cid:=cid
from sc,(select @sco=null,@rank:=0,@c_cid:=null) b
order by cid,score desc) a
where a.rk<3;
举报

相关推荐

0 条评论