zoukankan      html  css  js  c++  java
  • SQL gruop by(数据汇总查询)

    sql中gruop bygroup by/having 的用法

    在sql语句中可以指定 guoup by 子句对数据进行汇总
    //例一
    CREATE TABLE #tmp
    (
     rq NVARCHAR(10),
     shengfu NVARCHAR(1)
    )
    INSERT into #tmp select'2005-05-09','胜'
    Insert into #tmp select'2005-05-09','胜'
    insert into #tmp select'2005-05-09','负'
    insert into #tmp select'2005-05-09','负'
    insert into #tmp select'2005-05-10','胜'
    insert into #tmp select'2005-05-10','负'
    insert into #tmp select'2005-05-10','负'

    SELECT rq,sum(case when shengfu='胜' then 1 else 0 end)'胜',sum(case when shengfu='负' then 1 else 0 end)'负'
    from
    #tmp
    group by rq

    drop table #tmp

    例子二 group by/having
    数据表:student
    编号/姓名/专业/学分/性别
    id   name major     score sex
    1    jak    Chinese    40    f
    2    rain    Math        89    m
    3    leo    Phy          78    f
    4    jak    Math         76    f
    5    rain    Chinese   56    m
    6    leo    Math         97    f
    7    jak    Phy          45    f
    8    jak    Draw         87    f
    9    leo    Chinese    45    f


    现在我们要得到一个视图:
    要求查询性别为男生,并且列出每个学生的总成绩:
    SQL:

    select s.*,sum(s.score) from student s where sex='f' group by s.name
    Result:
    id   name major     score sex sum(s.score)
    1    jak    Chinese    40    f       248
    3    leo    Phy         78     f       220

    可以看到总共查到有两组,两组的学生分别是jak和leo,每一组都是同一个学生,这样我们就可以使用
    聚合函数了。
    只有使用了group by语句,才能使用如:count()、sum()之类的聚合函数。

    下面我们再对上面的结果做进一步的筛选,只显示总分数大于230的学生:
    SQL:
    select s.*,sum(s.score) from student s where sex='f' group by s.name having sum(s.score)>230

    Result:
    id   name major     score       sex   sum(s.score)
    1    jak    Chinese    40          f       248

    可见having于where的功能差不多。
    结论:
    HAVING 子句用来从分组的结果中筛选行。

  • 相关阅读:
    TLE: poj 1011 Sticks
    UVa 116 Unidirectional TSP
    csuoj 1215 稳定排序
    UVa 103 Stacking Boxes
    UVa 147 Dollars
    UVa 111 History Grading
    怎么在ASP.NET 2.0中使用Membership
    asp.net中如何删除cookie?
    ASP.NET中的HTTP模块和处理程序[收藏]
    NET开发中的一些小技巧
  • 原文地址:https://www.cnblogs.com/zhc088/p/1100617.html
Copyright © 2011-2022 走看看