logo头像
Snippet 博客主题

关于mysql聚合函数的学习

本文于 2138 天之前发表,文中内容可能已经过时。

关于mysql聚合函数的学习可以参考官方对于聚合函数的定义。
官方解释:mysql聚合函数

下面仅列出项目开发中使用频率较高的几种聚合函数

1. AVG()或者AVG([DISTINCT] expr)

官方解释:Returns the average value of expr. The DISTINCT option can be used to return the average of the distinct values of expr.
描述:Return the average value of the argument
翻译:返回待计算参数的平均值
使用方法:

现在存在一张学生表,建表语句如下    


CREATE TABLE `student` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `stu_no` varchar(20) DEFAULT NULL,
  `stu_name` varchar(100) DEFAULT NULL,
  `stu_age` int(2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

接下来我们新增三条数据

INSERT INTO student (stu_no, stu_name, stu_age)VALUES('C20190608001','张三','17'),('C20190608002','李四','18'),('C20190608003','王五','19');

现在表内容如下所示:

1	C20190608001	张三	17
2	C20190608002	李四	18
3	C20190608003	王五	19

需求:需要查询这张表所有人员平均年龄。(运行结果:18)

SELECT AVG(stu_age) FROM student;

当我们向表中再增加一条数据时:

INSERT INTO student (stu_no, stu_name, stu_age)VALUES('C20190608004','赵六','19');

需求:查询此表中不同年龄的学生的平均年龄。这个时候我们只需要对上一个SQL做简单修改。(运行结果:18)

SELECT AVG(DISTINCT stu_age) FROM student;

2. COUNT()或者COUNT([DISTINCT] expr,[expr…])

官方解释:Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement. The result is a BIGINT value.
描述:Return a count of the number of rows returned
翻译:返回查询结果行数
使用方法:
需求:返回学生表中的学生个数

SELECT COUNT(*) FROM student;

需求:返回学生表中不同的年龄有多少种

SELECT COUNT(DISTINCT stu_age) FROM student;

3.MAX()或者MAX([DISTINCT] expr)

官方描述:Return the maximum value.
翻译:返回最大值
官方解释:Returns the maximum value of expr. MAX() may take a string argument; in such cases,
it returns the maximum string value. See Section 8.3.1, “How MySQL Uses Indexes”.
The DISTINCT keyword can be used to find the maximum of the distinct values of expr,
however, this produces the same result as omitting DISTINCT.
使用方法: 同上述方法。

4.MIN()或者MAX([DISTINCT] expr)

官方描述:Return the minimum value.
翻译:返回最大值
官方解释:Returns the minimum value of expr. MIN() may take a string argument; in such cases,
it returns the minimum string value. See Section 8.3.1, “How MySQL Uses Indexes”. The DISTINCT
keyword can be used to find the minimum of the distinct values of expr, however, this produces the
same result as omitting DISTINCT.
使用方法: 同上述方法。

5.SUM()或者SUM([DISTINCT] expr)

官方描述:Return the sum.
翻译:返回合计值
官方解释:Returns the sum of expr. If the return set has no rows, SUM() returns NULL.
The DISTINCT keyword can be used to sum only the distinct values of expr.
使用方法: 同上述方法。

注:所有的DISTINCT,使用的时机为当需要统计去重之后的数据时使用。
希望大家在看过这一片博文之后能对mysql的聚合函数有一定的了解和学会简单的使用。
加油!