MySQL 知识量:16 - 40 - 165
有时我们需要的数据是某些行的汇总数据,例如查询结果一共有几行;所有行的和是多少;数据中的最大值、最小值、平均值是多少等等。
为此,MySQL提供了5个聚集函数:
函数 | 说明 |
---|---|
avg() | 返回某列的平均值 |
count() | 返回某列的行数 |
max() | 返回某列的最大值 |
min() | 返回某列的最小值 |
sum() | 返回某列值的和 |
avg()根据结果的行数和列值之和计算某列的平均值。
select avg(age) from student;
计算所有学生的平均年龄。结果为:
+----------+ | avg(age) | +----------+ | 10.8333 | +----------+
注意:avg()会忽略值为NULL的行。
count()用于计数。分两种用法:
使用count(*)计数,不会忽略NULL值。
使用count(列名)计数,会忽略NULL值。
select count(*) from student;
查询所有学生记录的条数。结果为:
+----------+ | count(*) | +----------+ | 6 | +----------+
max()用于查询列的最大值,它需要指定列名,且会忽略值为NULL的行。
select max(age) from student;
查询学生的最大年龄。结果为:
+----------+ | max(age) | +----------+ | 12 | +----------+
与max()相反的,min()用于查询列的最小值,它需要指定列名,且会忽略值为NULL的行。
select min(age) from student;
查询学生的最小年龄。结果为:
+----------+ | min(age) | +----------+ | 10 | +----------+
sum()函数用于计算返回列值的和,它需要指定列名,且会忽略值为NULL的行。
select sum(age) from student;
查询所有学生年龄的总和。结果为:
+----------+ | sum(age) | +----------+ | 65 | +----------+
通过使用distinct可以去除重复的值,结合聚集函数就可以聚集不同值。
select count(distinct age) from student;
查询学生中一共有几种不同的年龄。结果为:
+---------------------+ | count(distinct age) | +---------------------+ | 3 | +---------------------+
在select语句中,可以一次使用多个聚集函数。
select count(*) as total,avg(age) as avgofage,max(age) from student;
一次性查询学生的总数,年龄的平均数和最大年龄。结果为:
+-------+----------+----------+ | total | avgofage | max(age) | +-------+----------+----------+ | 6 | 10.8333 | 12 | +-------+----------+----------+
Copyright © 2017-Now pnotes.cn. All Rights Reserved.
编程学习笔记 保留所有权利
MARK:3.0.0.20240214.P35
From 2017.2.6