zoukankan      html  css  js  c++  java
  • 数据库查询终结版2———分组——连接

    select gradeid as 年级编号,COUNT(studentno) as 总人数
    from student
    group by gradeid

    一旦通过group by分组,那么我们只能获取组相关的信息,而不能获取组中成员的信息

           在select只能跟聚合函数和group by后面的列,其他列不允许

    2.多列分组

     例:根据年级和性别多列分组。

    select gradeid as  年级编号,gender as 性别,COUNT(studentno) as 总人数
    from student
    group by GradeId,Gender
    order by GradeId,Gender

    3.使用having子句进行分组筛选

    select gradeid as 年级编号,COUNT(studentno) as 总人数
    from student
    group by GradeId
    having COUNT(studentno)>3

     4.重中之重:**************************************************

    select SubjectId as 课程编号,AVG(studentresult) as 平均分  --04.投影结果
    from Result                         --01。定位到表
    where SubjectId<3  --,            --02.分组前第一道过滤
    group by SubjectId                  --03.分组
    having COUNT(studentno)>3           --05.分组后第二道过滤
    order by 课程编号 desc              --06.最后排序

    ************************************************************

    5.上机练习总结

    use Myschool
    --查总学时数,并按照升序排列
    select Gradeid,SUM(classhour) from subject
    group by gradeid
    order by SUM(classhour) desc
    --查询每个参加考试学生的平均分
    select studentno,AVG(studentresult) as 平均分 from Result
    group by StudentNo
    --查询每门课程的平均分,并按照降序排列
    select subjectid,AVG(studentresult) as 平均分 from Result
    group by SubjectId
    order by AVG(studentresult) desc
    --查询每门学生参加的所有考试的总分,并按照降序排列
    select studentno,sum(studentresult) as 总分 from Result
    group by StudentNo
    order by sum(studentresult)
    use myschool
    --学时超过50课程数
    select gradeid,sum(classhour) as 学时
    from Subject
    where ClassHour>50
    group by gradeid
    --每学期平均年龄
    select Gradeid,AVG(DATEDIFF(YY,birthday,getdate())) as 平均年龄
    from  Student 
    group by gradeid
    --
    select gradeid,COUNT(StudentNO) as 学生人数
    from Student
    where Address like '%北京%'
    group by GradeId 
    --平均分及格且成绩降序输出
    select studentno,AVG(StudentResult) as 平均后成绩 from result
    
    group by studentno
    having AVG(StudentResult)>=60
    order by 平均后成绩 desc
    select Subjectid,AVG(studentresult) from Result 
    where examdate='2013-03-22 08:45:28.000'
    group by SubjectId
    having AVG(studentresult)>=60

        我们在写代码是要清楚的知道代码执行的顺序,所以这篇博客的第四点时大家务必都要掌握的,再写代码时要先分析,不要急于求成,而上机练习的题目是要我们把知识点融会贯通,所以要明白每个知识点的用处,条件及意义。如:上面的代码就要先知道:where子句只能对分组前的数据进行筛选,而having则对分组后的数据进行筛选且后面一般跟聚合函数,而where却不能跟聚合函数来限制条件。且在遇到问题时我们要独立思考,看下面给我们的错误提示,这样才是一个优秀的程序员应该做的事。

       这次就聊到这里,下次见!!!

  • 相关阅读:
    HDU4507 吉哥系列故事――恨7不成妻(数位dp)
    UCF Local Programming Contest 2017 G题(dp)
    ICPC Latin American Regional Contests 2019 I题
    UCF Local Programming Contest 2017 H题(区间dp)
    HDU2089 不要62
    AcWing1084 数字游戏II(数位dp)
    UCF Local Programming Contest 2017 F题(最短路)
    Google Code Jam 2019 Round 1A Pylons(爆搜+贪心)
    AcWing1083 Windy数(数位dp)
    Vue
  • 原文地址:https://www.cnblogs.com/wth1129/p/4936522.html
Copyright © 2011-2022 走看看