zoukankan      html  css  js  c++  java
  • SQL练习

    学生成绩表(stuscore)

    表主键(id)、姓名(sname)、课程名称(subject)、分数(score)、学号(stuid)

    1、查询出每个学生的最高分数的科目信息及其学生姓名 学号(注意可能最高分数科目有多个。)

      思路:先通过学号将学生分组,获得学号及其科目最高分

      select s.stuid,s.sname,s.subject,s.score
      from stuscore s join
      (select stuid,max(score)as maxscore from stuscore group by stuid)ss
      on s.stuid=ss.stuid and s.score=ss.maxscore

    2、查询每个人总成绩并排名,并根据每个学生各科分数和倒序排列

      select stuid,sname,sum(score)as sumscore from stuscore group by stuid

      order by sumscore desc  

    3、计算每个人的平均成绩

      select stuid,sname,avg(score)as avgscore from stuscore group by stuid

    4、列出各门课目成绩最好的学生(考虑并列第一)

      思路:先根据课程 subject分组查询得到课程subject和课程对应的最高分

      select s.stuid,s.sname,s.subject,ss.maxscore from stuscore s
      join (select subject,max(score)as maxscore from stuscore group by subject)ss
      on s.subject=ss.subject and s.score=ss.maxscore

    5、统计如下:学号 姓名 语文 数学 英语 总分 平均分

      思路:例如获取语文成绩,先判断科目是否为语文,是则将其分数赋予;不是语

      文时令其分数为0,然后相加(语文成绩+0+0);总分:将学生分组后,获取每个

      学生的各科目成绩总和;平均分:各科目总分除以总科目数

      select stuid as 学号,sname as 姓名,

        sum(case when subject='语文' then score else 0 end)as 语文,
        sum(case when subject='数学' then score else 0 end)as 数学,
        sum(case when subject='英语' then score else 0 end)as 英语,
        sum(score)as 总分, #根据学生id、name分组后获得学生各科成绩总和
        sum(score)/count(subject)as 平均分
      from stuscore group by stuid,sname order by 总分 desc

    6、列出各门课程的平均成绩

      select subject,avg(score) from stuscore group by subject

    7、列出数学成绩的排名(显示字段:排名【非原表中的字段,sql中用pm表示】,姓名,成绩)

      详解见:http://www.cnblogs.com/northern-light/p/8494711.html

      select (@i:=@i+1)pm,s.* from stuscore s,(select @i:=0)t 

      where s.subject='数学' order by score desc

    8、列出数学成绩在2-3名的学生

      思路:先插入排序列(pm表示顺序,第几名)

      select * from 

      (select (@i:=@i+1)pm,s.* from stuscore s,(select @i:=0)t where s.subject='数学' order by score desc) t2
      where t2.pm between 2 and 3;

    9、写出李四的数学成绩的排名

      select * from 

      (select (@i:=@i+1)pm,s.* from stuscore s,(select @i:=0)t where s.subject='数学' order by score desc)t2
      where t2.sname='李四';

    10、统计如下:课程 不及格(0-59)个 良好(60-80)个 优秀(81-100)个

      select subject as 课程,

        (select count(stuid) from stuscore where score <60 and subject=t1.subject)as 不及格,
        (select count(stuid) from stuscore where score between 60 and 80 and subject=t1.subject)as 良好,
        (select count(stuid) from stuscore where score >80 and subject=t1.subject)as 优秀
      from stuscore t1 group by t1.subject

     

    人生没有彩排,每天都是现场直播!
  • 相关阅读:
    「考试」省选6
    「考试」省选5
    「考试」省选4
    「笔记」拉格朗日插值
    数学专测
    「笔记」$exlucas$
    「总结」$dp1$
    「总结」达哥数学专项
    「总结」筛法2
    「总结」莫反2
  • 原文地址:https://www.cnblogs.com/northern-light/p/8494984.html
Copyright © 2011-2022 走看看