美文网首页
50道SQL练习题

50道SQL练习题

作者: 神农架村姑 | 来源:发表于2019-02-07 10:29 被阅读2次

    SQL SERVER

    数据表

    Student student.PNG Course course.PNG Teacher teacher.PNG Score scPNG.PNG

    1.查询" 01 "课程比" 02 "课程成绩高的学生的信息及课程分数

    select * from student as s
    right join(
        select sc1.sid, sc1score, sc2score from
            (select sid, score as sc1score from sc where cid='01') as sc1,
            (select sid, score as sc2score from sc where cid='02') as sc2
            where sc1.sid = sc2.sid and sc1score > sc2score
    ) as t
    on s.sid = t.sid
    
    1.PNG

    1.3 查询不存在" 01 "课程但存在" 02 "课程的情况

    select * from sc where cid = '02' and sid not in (select sid from sc where cid = '01')
    

    2.查询平均成绩大于等于 60 分的同学的学生编号和学生姓名和平均成绩

    select s.sid, s.sname, avgscore from student as s
    right join 
    (select sid, avg(score) as avgscore from sc group by sid) as t
    on t.sid = s.sid
    where avgscore>=60
    
    2.PNG

    3.查询在 SC 表存在成绩的学生信息

    select * from student where sid in (select distinct sid from sc)
    

    4.查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩(没成绩的显示为null)

    select s.sid,s.sname, t.CountOfCourses, t.SumOfScore from student as s 
    left join (
        select sid,count(cid) as CountOfCourses,sum(score) as SumOfScore from sc group by sid
    )t
    on s.sid=t.sid
    
    4.PNG

    4.1 查有成绩的学生信息
    这一题涉及in和exists的用法,在小表中,两种方法的效率都差不多
    当后表的记录数量非常大的时候,选用exists比in要高效很多.

    IN()只执行一次,它查出B表中的所有id字段并缓存起来。之后,检查A表的id是否与B表中的id相等,如果相等则将A表的记录加入结果集中,直到遍历完A表的所有记录。可以看出,当B表数据较大时不适合使用in(),因为它会B表数据全部遍历一次

    Exists()会执行A.length次,它并不缓存exists()结果集,因为exists()结果集的内容并不重要。EXISTS用于检查subquery是否至少会返回一行数据,该subquery实际上并不返回任何数据,而是返回True或False。

    select * from student
    where exists (select 8 from sc where sc.sid=student.sid)
    
    1. 查询「李」姓老师的数量
    select count(*) from teacher where tname like N'李%'
    
    1. 查询学过「张三」老师授课的同学的信息
    select student.* from student, sc
    where student.sid=sc.sid and sc.cid in (
    select cid from course, teacher
    where course.TId=teacher.TId and teacher.tname=N'张三')
    

    多表联合查询

    select student.* from student, sc, course, teacher
        where student.sid=sc.sid
        and sc.cid=course.cid
        and course.TId=teacher.TId
        and teacher.Tname=N'张三'
    
    1. 查询没有学全所有课程的同学的信息
    select * from student where sid not in(
        select t.sid from (
            select sid, count(cid) as c from sc
            group by sid
            having count(cid)=3
            --此处不应为3,应为(select count(cid) from course)
        )t
    )
    
    1. 查询至少有一门课与学号为" 01 "的同学所学相同的同学的信息
    select * from student where sid in(
        select distinct sid from sc where sc.cid in(
        select cid from sc where sid='01'))
    
    1. 查询和" 01 "号的同学学习的课程 完全相同的其他同学的信息
      我的解法:没选“01”同学以外的课,且选课数量与“01”同学完全一样,即全等
      这里的解法是:https://zhuanlan.zhihu.com/p/32137597 把所有学生这几门课(01/02/03)的成绩列出来,如果有null,表示该学生没选这门课,排除这些学生,即选了“01”同学的所有课(01/02/03)的同学。但如果他还选了04/05号课呢?这个解法不能表示“完全相同”
    //step1 选出“01”号学生选的所有课程
     select cid from sc where sid='01'
    
    //step2 选出 选了 除step1以外课程 的所有学生,"!=all" 就是 "not in
     select distinct sid from sc where sc.cid !=all(
        select cid from sc where sid='01')
    
    //step3 选出不在step2里面的所有学生,
    //即选了“01”号学生选的某几门课,且没选和他不一样课程的学生
    select sid from sc where sid not in(
        select distinct sid from sc where sc.cid !=all(
        select cid from sc where sid='01'))
    
    //step4 计算这些学生的课程数量,
    //等于“01”学生所选的课程数量时,表示他们完全选了一模一样的课
    select sid, count(sid) from sc where sid not in(
        select distinct sid from sc where sc.cid !=all(
        select cid from sc where sid='01'))
    group by sid
    having count(sid)=(select count(cid) from sc where sid='01')
    
    //step5 在student表查找学生信息
    select * from student where sid in (
        select sid from sc where sid not in(
            select distinct sid from sc where sc.cid !=all(
            select cid from sc where sid='01'))
        group by sid
        having count(sid)=(select count(cid) from sc where sid='01'))
    
    1. 查询没学过"张三"老师讲授的任一门课程的学生姓名
      针对张三老师的所有课,在sc表中选出这些课有成绩的同学,即选了张三老师任意一门课的同学。反之 not in就表示没选任意一门课
    select sname from student where sid not in(
      select sid from sc where cid in (
        select cid from course, teacher where course.tid=teacher.tid and teacher.Tname=N'张三'
      )
    )
    
    1. 查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩
    select t1.sid,student.sname,t1.avgscore from student,(
        select t.sid, avg(score) as avgscore from (
            select * from sc where score<60)t
        group by t.sid having count(cid)>=2)t1
    where t1.sid=student.sid
    
    1. 检索" 01 "课程分数小于 60,按分数降序排列的学生信息
    select student.* from sc,student where 
      sc.sid=student.sid 
      and sc.cid='01' 
      and sc.score<60 
    order by sc.score desc
    
    1. 按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩
    select sc.sid, sc.CId, sc.score, t.avgscore from sc,
        (select sid, avg(score) as avgscore from sc 
        group by sid)t
    where sc.sid=t.sid
    order by t.avgscore desc
    
    1. 查询各科成绩最高分、最低分和平均分:

    (不会做)

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

    STEP1. 先解那几个率,先把某率的人数找出来,除以选修人数即可。
    方法是满足条件的赋值为1,不满足的赋值为0,把1的数量求和即为满足条件的人数。
    
    select *,
    case 
        when sc.score>=60 then 1 
        else 0 
    end as 及格率
    from sc
    
    1.PNG
    step2. 求每科的及格人数
    
    select cid, sum(
    case 
        when sc.score>=60 then 1 
        else 0 
    end) as 及格人数
    from sc
    group by cid
    
    2.PNG
    step3. 照这个思路可以把几个率的人数都求出来
    
    select sc.CId ,count(*)as 选修人数,max(sc.score)as 最高分,min(sc.score)as 最低分,AVG(sc.score)as 平均分,
    sum(case when sc.score>=60 then 1 else 0 end) as 及格人数,
    sum(case when sc.score>=70 and sc.score<80 then 1 else 0 end ) as 中等人数,
    sum(case when sc.score>=80 and sc.score<90 and sc.score<80 then 1 else 0 end )as 优良人数,
    sum(case when sc.score>=90 then 1 else 0 end )as 优秀人数 
    from sc
    GROUP BY sc.CId
    
    3.PNG
    step4. 接下来就简单了,某人数除以选修总人数即为某率;
    再把排序写上;把对应的课程名找出来
    注意:两个整数用“/”相除,会向下取整。要用cast as float变为小数
    
    select course.Cname, t.* from course, (
        select sc.CId,count(*)as 选修人数,max(sc.score)as 最高分,min(sc.score)as 最低分,AVG(sc.score)as 平均分,
        cast(sum(case when sc.score>=60 then 1 else 0 end )as float)/count(*)as 及格率,
        cast(sum(case when sc.score>=70 and sc.score<80 then 1 else 0 end )as float)/count(*)as 中等率,
        cast(sum(case when sc.score>=80 and sc.score<90 and sc.score<80 then 1 else 0 end )as float)/count(*)as 优良率,
        cast(sum(case when sc.score>=90 then 1 else 0 end )as float)/count(*)as 优秀率 
        from sc GROUP BY sc.CId) t 
    where course.cid=t.cid
    order by 选修人数 desc, cid
    
    4.PNG
    1. 按各科成绩进行排序,并显示排名,
      Score 重复时保留名次空缺 / Score 重复时合并名次

    rank() 函数

    select *, 
    row_number() over (PARTITION BY cid ORDER BY score DESC) as row_number,
    RANK() OVER (PARTITION BY cid ORDER BY score DESC) AS Rank,
    dense_rank() over (PARTITION BY cid ORDER BY score DESC) AS dense_Rank 
    from sc
    
    1.PNG

    解法2. 也可以不用T-SQL

    https://www.jianshu.com/p/476b52ee4f1b 思路清奇

    step1. 把一个学生的各科成绩和其他学生的各科成绩放到一起
    select * from sc as a left join sc as b
    on a.cid = b.cid
    
    1.PNG
    STEP2. 看某学生某门课比哪些学生成绩高
    
    select * from sc as a left join sc as b
    on a.cid = b.cid and a.score>b.score
    
    2.PNG
    step3. 算出某学生某门课比几个人成绩高
    
    select a.sid, a.cid, a.score, count(b.score) as rank
    from sc as a left join sc as b 
    on a.score>b.score and a.cid = b.cid
    group by a.cid, a.sid, a.score
    
    3.PNG
    step4. 以上排名是数越大排名越靠前,如何反过来?
    按分数低的排序就好了,即把大于号>改成小于号<
    
    select a.cid, a.sid, a.score, count(b.score)+1 as rank
    from sc as a 
    left join sc as b 
    on a.score<b.score and a.cid = b.cid
    group by a.cid, a.sid,a.score
    order by a.cid, rank;
    
    1. 查询学生的总成绩,并进行排名,总分重复时保留名次空缺
      16.1 查询学生的总成绩,并进行排名,总分重复时不保留名次空缺
    select *, RANK() OVER (ORDER BY sums DESC) AS "16 Rank", 
        dense_RANK() OVER (ORDER BY sums DESC) AS "16.1 Rank" 
    from(
        select sid, sum(score) as sums from sc
        group by sid)t
    order by t.sums desc
    
    1.PNG
    1. 统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[60-0] 及所占百分比
    select sc.cid, course.Cname, 
        sum(case when score>=85 then 1 else 0 end) as '100-85',
        cast(sum(case when score>=85 then 1 else 0 end)/cast(count(*) as decimal(5,2))as decimal(5,2)) as 'rate',
        sum(case when score<85 and score>=70 then 1 else 0 end) as '85-70',
        cast(sum(case when score<85 and score>=70 then 1 else 0 end)/cast(count(*) as decimal(5,2))as decimal(5,2)) as 'rate',
        sum(case when score<70 and score>=60 then 1 else 0 end) as '70-60',
        cast(sum(case when score<70 and score>=60 then 1 else 0 end)/cast(count(*) as decimal(5,2)) as decimal(5,2)) as 'rate',
        sum(case when score<60 then 1 else 0 end) as '60-0',
        cast(sum(case when score<60 then 1 else 0 end)/cast(count(*) as decimal(5,2)) as decimal(5,2)) as 'rate'
    from sc left join course on sc.cid=course.cid
    group by sc.cid,course.Cname
    order by cid 
    
    1.PNG
    1. 查询各科成绩前三名的记录
    select * from (
      select cid, sid, score, 
        rank() over (partition by cid order by score desc) as rank 
      from sc
    )t where rank <= 3
    

    别人的写法 不理解

    select *
    from sc  
    where  (select count(*) from sc as a where sc.CId =a.CId and  sc.score <a.score )<3
    ORDER BY CId asc,sc.score desc
    
    1. 查询每门课程被选修的学生数
    select cid, count(*) from sc 
    group by cid
    
    1. 查询出只选修两门课程的学生学号和姓名
    select s.sid, s.sname, count(sc.sid) as 选课数 from sc 
    left join student as s on sc.sid=s.sid
    group by s.sid, s.sname having count(sc.sid)=2
    

    21.查询男生、女生人数

    select ssex, count(ssex) from student group by ssex
    
    1. 查询名字中含有「风」字的学生信息
    select * from student where sname like N'%风%'
    

    23.查询同名同姓学生名单,并统计同名人数

    select student.*,t.n from student, (
    select sname,count(sname) as n from student 
    group by sname having count(sname)>1 )t
    where student.sname=t.sname
    

    24.查询 1990 年出生的学生名单

    year() 函数

    select * from student where year(sage)=1990
    

    25.查询每门课程的平均成绩,结果按平均成绩降序排列,平均成绩相同时,按课程编号升序排列

    select cid, avg(score) as avg from sc group by cid
    order by avg desc, cid
    

    26.查询平均成绩大于等于 85 的所有学生的学号、姓名和平均成绩
    (其实应该把join写在group by的外面)

    select sc.sid, student.sname, avg(score) as avg from sc 
    left join student on sc.sid=student.sid
    group by sc.sid, student.sname having avg(score)>=85
    
    1. 查询课程名称为「数学」,且分数低于 60 的学生姓名和分数
    select sc.sid, student.sname, sc.cid, sc.score from sc, student, course 
    where sc.sid=student.sid and sc.cid=course.cid
    and course.cname=N'数学' and sc.score>60
    
    1. 查询所有学生的课程及分数情况(存在学生没成绩,没选课的情况)
    select s.sid, s.sname, sc.cid, sc.score from student as s 
    left join sc on s.sid=sc.sid
    
    1. 查询任何一门课程成绩在 70 分以上的姓名、课程名称和分数
    select s.sid, s.sname, c.cid, c.cname, sc.score from student as s, course as c, sc 
    where s.sid=sc.sid and c.cid=sc.cid and sc.score>70
    

    30.查询存在不及格的课程

    select distinct course.cid, course.cname from course, sc 
    where sc.cid=course.cid and sc.score<60
    

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

    select sc.sid, student.Sname from sc, student 
    where sc.sid=student.sid
    and sc.cid='01' and sc.score>=80
    
    1. 求每门课程的学生人数
    select cid, count(cid) from sc group by cid
    
    1. 成绩不重复,查询选修「张三」老师所授课程的学生中,成绩最高的学生信息及其成绩
    select top 1 
    s.*, sc.CId, sc.score from student as s, sc, course as c, teacher as t 
    where s.sid=sc.sid and sc.cid=c.cid and c.TId=t.TId and t.Tname=N'张三'
    
    1. 成绩有重复的情况下,查询选修「张三」老师所授课程的学生中,成绩最高的学生信息及其成绩
    select * from (
    select s.*, sc.CId, sc.score, rank() over (order by sc.score desc) as rank
    from student as s, sc, course as c, teacher as t 
    where s.sid=sc.sid and sc.cid=c.cid and c.TId=t.TId and t.Tname=N'张三'
    )t where t.rank=1
    
    1. 查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩
      我理解的是,对于每个课程,找成绩相同的学生
    select sc.* from sc, (
        select cid, score, count(score) as n from sc group by cid, score
        having count(score)>1)t
    where sc.cid=t.cid and sc.score=t.score
    

    别人理解为对于与每个学生,找不同课程成绩相同的记录

    select distinct a.* from sc as a
    inner join sc as b
    on a.sid = b.sid
    and a.cid != b.cid
    and a.score = b.score
    

    36.查询每门功成绩最好的前两名

    select * from (
    select *, rank() over (partition by cid order by score desc) as rank from sc)t
    where t.rank<=2
    

    37.统计每门课程的学生选修人数(超过 5 人的课程才统计)

    select cid,count(*) from sc group by cid having count(*)>5
    

    38.检索至少选修两门课程的学生学号

    select sid,count(*) from sc group by sid having count(*)>=2
    
    1. 查询选修了全部课程的学生信息
    select student.* from student, (
        select sid, count(*) as n from sc 
        group by sid having count(*)= 
        (select count(CID) from course)
    )t where student.sid=t.sid
    

    40.查询各学生的年龄,只按年份来算

    select sid, sname,datediff(YYYY, sage,getdate()) as age from student
    
    1. 按照出生日期来算,当前月日 < 出生年月的月日则,年龄减一
    select sid, sname, sage,
    case
        when month(getdate())<month(sage) or (month(getdate())=month(sage) and day(getdate())<day(sage))
            then datediff(YYYY, sage,getdate())-1
        else datediff(YYYY, sage,getdate())
    end as age,
    from student
    

    42.查询本周过生日的学生

    不能直接用 datepart(week,getdate())=datepart(week,sage),
    因为1990年3月1日 returns 1990年的第几周,2019年3月1日 returns 2019年的第几周,二者不一定相等,如果恰巧是周六周日,就有可能相差1

    所以要把学生生日在当前年份中找第几周

    select sid, sname, sage from student where
    datepart( week,DATEFROMPARTS(year(getdate()), month(sage),day(sage)) )-datepart(week,getdate())=0
    
    1. 查询下周过生日的学生
    select sid, sname, sage from student where
    datepart( week,DATEFROMPARTS(year(getdate()), month(sage),day(sage)) )-datepart(week,getdate())=1
    

    44.查询本月过生日的学生

    select sid, sname, sage from student
    where datepart(m,sage)-datepart(m,getdate())=0
    

    45.查询下月过生日的学生

    select sid, sname, sage from student
    where datepart(m,sage)-datepart(m,getdate())=1
    

    疑问

    1. @变量还不太会写

    2. 第36提 这种写法不太懂

    select *
    from sc as t1
    where (select count(*) from sc as t2 where t1.CId=t2.CId and t2.score >t1.score)<2
    ORDER BY t1.CId

    相关文章

      网友评论

          本文标题:50道SQL练习题

          本文链接:https://www.haomeiwen.com/subject/mnmwsqtx.html