zoukankan      html  css  js  c++  java
  • SQL中GROUP BY的使用

    1、概述:

      “Group By”从字面意义上理解就是根据“By”指定的规则对数据进行分组,所谓的分组就是将一个“数据集”划分成若干个“小区域”,然后针对若干个“小区域”进行数据处理。


    2、简单的group by

    select 类别, sum(数量) as 数量之和
    from A
    group by 类别

    3、group by

    select 类别, sum(数量) AS 数量之和
    from A
    group by 类别
    order by sum(数量) desc

    4、group byselect指定的字段:

    select 类别, sum(数量) as 数量之和, 摘要
    from A
    group by 类别
    order by 类别 desc

    5、group by all

    select 类别, 摘要, sum(数量) as 数量之和
    from A
    group by all 类别, 摘要

     6、havingwhere的区别:

      wherewhere 子句的作用是在对查询结果进行分组前,将不符合where条件的行去掉,即在分组之前过滤数据,where条件中不能包含聚组函数,使用where条件过滤出特定的行。

      having:having 子句的作用是筛选满足条件的组,即在分组之后过滤数据,条件中经常包含聚组函数,使用having 条件过滤出特定的组,也可以使用多个分组标准进行分组。

    select 类别, sum(数量) as 数量之和 from A
    group by 类别
    having sum(数量) > 18
    select 类别, SUM(数量)from A
    where 数量 gt;8
    group by 类别
    having SUM(数量) gt; 10

     7、computecompute by

    select *
    from A
    where 数量>8
    compute max(数量),min(数量),avg(数量)

      compute子句能够观察“查询结果”的数据细节或统计各列数据,返回结果由select列表和compute统计结果组成。

    select *
    from A
    where 数量>8
    order by 类别
    compute max(数量),min(数量),avg(数量) by 类别
    • compute子句必须与order by子句用一起使用。
    • compute...bygroup by相比,group by只能得到各组数据的统计结果,而不能看到各组数据。
  • 相关阅读:
    最小瓶颈路
    HASH处理KMP算法
    忠诚
    程序自动分析
    图书管理
    银牛派对
    平均数
    抓住那头牛
    P2135 方块消除
    CSPS前最后一次模拟赛----爆炸的全过程
  • 原文地址:https://www.cnblogs.com/solvit/p/9966381.html
Copyright © 2011-2022 走看看