MySQL

MySQL 知识量:16 - 40 - 165

5.3 汇总数据><

聚集函数- 5.3.1 -

有时我们需要的数据是某些行的汇总数据,例如查询结果一共有几行;所有行的和是多少;数据中的最大值、最小值、平均值是多少等等。

为此,MySQL提供了5个聚集函数:

函数说明
avg()返回某列的平均值
count()返回某列的行数
max()返回某列的最大值
min()返回某列的最小值
sum()返回某列值的和

AVG()- 5.3.2 -

avg()根据结果的行数和列值之和计算某列的平均值。

select avg(age) from student;

计算所有学生的平均年龄。结果为:

+----------+
| avg(age) |
+----------+
|  10.8333 |
+----------+

注意:avg()会忽略值为NULL的行。

COUNT()- 5.3.3 -

count()用于计数。分两种用法:

  1. 使用count(*)计数,不会忽略NULL值。

  2. 使用count(列名)计数,会忽略NULL值。

select count(*) from student;

查询所有学生记录的条数。结果为:

+----------+
| count(*) |
+----------+
|        6 |
+----------+

MAX()- 5.3.4 -

max()用于查询列的最大值,它需要指定列名,且会忽略值为NULL的行。

select max(age) from student;

查询学生的最大年龄。结果为:

+----------+
| max(age) |
+----------+
|       12 |
+----------+

MIN()- 5.3.5 -

与max()相反的,min()用于查询列的最小值,它需要指定列名,且会忽略值为NULL的行。

select min(age) from student;

查询学生的最小年龄。结果为:

+----------+
| min(age) |
+----------+
|       10 |
+----------+

SUM()- 5.3.6 -

sum()函数用于计算返回列值的和,它需要指定列名,且会忽略值为NULL的行。

select sum(age) from student;

查询所有学生年龄的总和。结果为:

+----------+
| sum(age) |
+----------+
|       65 |
+----------+

聚集不同值- 5.3.7 -

通过使用distinct可以去除重复的值,结合聚集函数就可以聚集不同值。

select count(distinct age) from student;

查询学生中一共有几种不同的年龄。结果为:

+---------------------+
| count(distinct age) |
+---------------------+
|                   3 |
+---------------------+

组合聚集函数- 5.3.8 -

在select语句中,可以一次使用多个聚集函数。

select count(*) as total,avg(age) as avgofage,max(age) from student;

一次性查询学生的总数,年龄的平均数和最大年龄。结果为:

+-------+----------+----------+
| total | avgofage | max(age) |
+-------+----------+----------+
|     6 |  10.8333 |       12 |
+-------+----------+----------+