search
HomeDatabaseMysql TutorialGROUP BY与COUNT用法详解

GROUP BY与COUNT用法详解

Jun 07, 2016 pm 02:50 PM
countintroducefunctionusagepolymerizationDetailed explanation

聚合函数 在介绍GROUP BY 和 HAVING 子句前,我们必需先讲讲sql语言中一种特殊的函数:聚合函数, 例如SUM, COUNT, MAX, AVG等。这些函数和其它函数的根本区别就是它们一般作用在多条记录上。 SELECT SUM(population) FROM bbc 这里的SUM作用在所有返回记录

聚合函数

    在介绍GROUP BY 和 HAVING 子句前,我们必需先讲讲sql语言中一种特殊的函数:聚合函数, 例如SUM, COUNT, MAX, AVG等。这些函数和其它函数的根本区别就是它们一般作用在多条记录上。

SELECT SUM(population) FROM bbc

这里的SUM作用在所有返回记录的population字段上,结果就是该查询只返回一个结果,即国家的总人口数。

GROUP BY用法

    Group By语句从英文的字面意义上理解就是“根据(by)一定的规则进行分组(Group)”。它的作用是通过一定的规则将一个数据集划分成若干个小的区域,然后针对若干个小区域进行数据处理。
注意:group by 是先排序后分组;
    举例子说明:如果要用到group by 一般用到的就是“每这个字段” 例如说明现在有一个这样的表:每个部门有多少人 就要用到分组的技术

<code class=" hljs sql"><span class="hljs-operator"><span class="hljs-keyword">select</span> DepartmentID <span class="hljs-keyword">as</span> <span class="hljs-string">'部门名称'</span>,
<span class="hljs-aggregate">COUNT</span>(*) <span class="hljs-keyword">as</span> <span class="hljs-string">'个数'</span> <span class="hljs-keyword">from</span> BasicDepartment <span class="hljs-keyword">group</span> <span class="hljs-keyword">by</span> DepartmentID</span></code>

    这个就是使用了group by +字段进行了分组,其中我们就可以理解为我们按照了部门的名称ID,DepartmentID将数据集进行了分组;然后再进行各个组的统计数据分别有多少;
    通俗一点说:group by 字段1,字段2。。。(整个表中不止这两个字段)表示数据集中字段1相等,字段2也相等的数据归为一组,只显示一条数据。那么你可以对字段3进行统计(求和,求平均值等)

注意
select DepartmentID,DepartmentName from BasicDepartment group by DepartmentID

–将会出现错误

    选择列表中的列 ‘DepartmentName’ 无效,因为该列没有包含在聚合函数或 GROUP BY 子句中。这就是我们需要注意的一点,如果在返回集字段中,这些字段要么就要包含在Group By语句的后面,作为分组的依据;要么就要被包含在聚合函数中。为什么呢,根据前面的说明:DepartmentID相等的数据归为一组,只显示一条记录,那如果数据集中有这样三条数据。

      DepartmentID                              DepartmentName
            dept001                                            技术部
            dept001                                            综合部
            dept001                                            人力部
那我只能显示一条记录,我显示哪个?没法判断了。到这里有三种选择:

  1. 把DepartmentName也加入到分组的条件里去(GROUP BY DepartmentID,DepartmentName),那这三条记录就是三个分组。
  2. 不显示DepartmentName字段。
  3. 用聚合函数把这三条记录整合成一条记录count(DepartmentName)

WHERE和 HAVING

    HAVING子句可以让我们筛选成组后的各组数据。HAVING子句可以使用聚合函数
    WHERE子句在聚合前先筛选记录.也就是说作用在GROUP BY 子句和HAVING子句前. WHERE字句中不能使用聚合函数
    举例说明:
    一、显示每个地区的总人口数和总面积.

<code class=" hljs sql"><span class="hljs-operator"><span class="hljs-keyword">SELECT</span> region, <span class="hljs-aggregate">SUM</span>(population), <span class="hljs-aggregate">SUM</span>(area)
<span class="hljs-keyword">FROM</span> bbc
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> region</span></code>

    先以region把返回记录分成多个组,这就是GROUP BY的字面含义。分完组后,然后用聚合函数对每组中的不同字段(一或多条记录)作运算。

    二、 显示每个地区的总人口数和总面积.仅显示那些面积超过1000000的地区。

<code class=" hljs sql"><span class="hljs-operator"><span class="hljs-keyword">SELECT</span> region, <span class="hljs-aggregate">SUM</span>(population), <span class="hljs-aggregate">SUM</span>(area)
<span class="hljs-keyword">FROM</span> bbc8 F4 w2 v( P- f
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> region
<span class="hljs-keyword">HAVING</span> <span class="hljs-aggregate">SUM</span>(area)><span class="hljs-number">1000000</span></span></code>

    在这里,我们不能用where来筛选超过1000000的地区,因为表中不存在这样一条记录。相反,HAVING子句可以让我们筛选成组后的各组数据

    需要注意说明:当同时含有where子句、group by 子句 、having子句及聚集函数时,执行顺序如下:
    执行where子句查找符合条件的数据;
    使用group by 子句对数据进行分组;对group by 子句形成的组运行聚集函数计算每一组的值;最后用having 子句去掉不符合条件的组。
    having子句和where子句都可以用来设定限制条件以使查询结果满足一定的条件限制。
    having子句限制的是组,而不是行。where子句中不能使用聚集函数,而having子句中可以。

GROUP BY 与COUNT的一些复杂用法

直接用例子来说明吧
现有表:居民区表:DW_DM_RE_RC,部分字段如下

<code class=" hljs cs"><span class="hljs-keyword">select</span> AREA_ID,AREA_NAME,CITY_ID,CITY_NAME,RC_ID,RC_NAME,RC_TYPE_ID,RC_TYPE_NAME,RC_ADDRESS,FLOOR_CNT,BUILDING_CNT <span class="hljs-keyword">from</span> DW_DM_RE_RC</code>

这里写图片描述
数据主要集中在宿迁和无锡两个地市。
现需要根据AREA_ID和CITY_NAME进行分组,且显示同一个AREA_ID的数据数量。(AREA_ID和AREA_NAME相关联,CITY_ID,CITY_NAME相关联)
第一步:
sql1:

<code class=" hljs sql"><span class="hljs-operator"><span class="hljs-keyword">select</span> <span class="hljs-aggregate">COUNT</span>(*) <span class="hljs-keyword">as</span> <span class="hljs-aggregate">COUNT</span>,AREA_ID,AREA_NAME,CITY_ID,CITY_NAME <span class="hljs-keyword">from</span> DW_DM_RE_RC
<span class="hljs-keyword">group</span> <span class="hljs-keyword">by</span> AREA_ID,AREA_NAME,CITY_ID,CITY_NAME</span></code>

这里写图片描述
这里COUNT显示的是以AREA_ID和CITY_NAME为条件进行分组的,
表示AREA_ID=510,CITY_NAME=’滨湖区’(无锡市滨湖区)的数据有131条,表示AREA_ID=510,CITY_NAME=’宜兴’(无锡市宜兴区)的数据有131条,表示AREA_ID=527,CITY_NAME=’泗洪’(宿迁市泗洪区)的数据有101条,但我需要的是属于AREA_ID=510(无锡市,不管哪个区)的总数据量有多少。由此得到启发,可以将sql1的查询结果当做结果集,在上面再进行一次查询。
sql2:

<code class=" hljs sql"><span class="hljs-operator"><span class="hljs-keyword">SELECT</span> AREA_ID,AREA_NAME,<span class="hljs-aggregate">SUM</span>(<span class="hljs-aggregate">COUNT</span>),CITY_ID,CITY_NAME  <span class="hljs-keyword">FROM</span> (
<span class="hljs-keyword">select</span> <span class="hljs-aggregate">COUNT</span>(*) <span class="hljs-keyword">as</span> <span class="hljs-aggregate">COUNT</span>,AREA_ID,AREA_NAME,CITY_ID,CITY_NAME <span class="hljs-keyword">from</span> DW_DM_RE_RC
<span class="hljs-keyword">group</span> <span class="hljs-keyword">by</span> AREA_ID,AREA_NAME,CITY_ID,CITY_NAME
)TEST <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> AREA_ID,AREA_NAME,CITY_ID,CITY_NAME</span></code>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools