Home > Database > Mysql Tutorial > body text

How to write grouping function in mysql

下次还敢
Release: 2024-05-01 20:37:00
Original
1069 people have browsed it

MySQL 中的分组函数按指定列分组数据,并对每个组计算聚合值。分组函数包括 COUNT、SUM、AVG、MIN 和 MAX。HAVING 子句可过滤分组结果,保留满足条件的组。分组后,其他列按行分组,HAVING 子句条件应用于分组结果,未指定则假定为 TRUE。可使用多个 GROUP BY 和 HAVING 子句创建复杂分组。

How to write grouping function in mysql

MySQL 中的分组函数

分组函数用于根据给定列对数据进行分组,并对每个组计算聚合值。

语法:

<code class="sql">GROUP BY col1, col2, ...
HAVING condition</code>
Copy after login

参数:

  • GROUP BY:指定分组列。
  • HAVING:用于过滤分组结果,仅保留满足条件的组。

常用分组函数:

  • COUNT:返回指定列中非空值的计数。
  • SUM:返回指定列中所有值的总和。
  • AVG:返回指定列中所有值的平均值。
  • MIN:返回指定列中最小值。
  • MAX:返回指定列中最大值。

举例:

<code class="sql">SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING total_salary > 50000;</code>
Copy after login

该查询将员工按部门分组,并计算每个部门的总工资。它只保留总工资大于 50,000 的部门。

要点:

  • 分组后,原始数据中的所有其他列将按行分组。
  • HAVING 子句中的条件应用于分组结果,而不是原始数据。
  • 如果未指定 HAVING 子句,则假定其为 TRUE,所有分组都将显示。
  • 可以使用多个 GROUP BY 和 HAVING 子句来创建更复杂的分组。

The above is the detailed content of How to write grouping function in mysql. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!