Table of Contents
聚合函数
GROUP BY用法
WHERE和 HAVING
GROUP BY 与COUNT的一些复杂用法
Home Database Mysql Tutorial GROUP BY与COUNT用法详解

GROUP BY与COUNT用法详解

Jun 07, 2016 pm 02:50 PM
count introduce function usage polymerization Detailed 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>
Copy after login

这个就是使用了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>
Copy after login

先以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>
Copy after login

在这里,我们不能用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>
Copy after login

这里写图片描述
数据主要集中在宿迁和无锡两个地市。
现需要根据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>
Copy after login

这里写图片描述
这里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>
Copy after login
Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

Detailed introduction of Samsung S24ai functions Detailed introduction of Samsung S24ai functions Jun 24, 2024 am 11:18 AM

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

See all articles