目录
1.聚合函数
函数 | 说明 |
count( [DISTINCT] 参数 ) | 返回查询到的数据的数量 |
sum ( [DISTINCT] 参数) | 返回查询到的数据的总和,不是数字没有意义 |
avg ( [DISTINCT] 参数 ) | 返回查询到的数据的平均值,不是数字没有意义 |
max ( [DISTINCT] 参数) | 返回查询到的数据的最大值,不是数字没有意义 |
min ( [DISTINCT] 参数) | 返回查询到的数据的最小值,不是数字没有意义 |
什么是聚合函数?
聚合统计一定是直接或者间接统计列方向的某些数据。列方向上一定是相同属性的。对于行方向上,可以直接使用select 表达式相加/相乘等进行统计。
1.1 count
当想查看,当前筛选出来的结果有几条时,可以使用count函数
使用 * 做统计,NULL不纳入统计。也可以用 count(1)等表达式进行统计
mysql> select count(*) from exam_result;
+----------+
| count(*) |
+----------+
| 7 |
+----------+
mysql> select count(name) from exam_result;
+-------------+
| count(name) |
+-------------+
| 7 |
+-------------+
1 row in set (0.00 sec)
查看去重之后的统计个数
mysql> select count(distinct math) from exam_result;
+----------------------+
| count(distinct math) |
+----------------------+
| 6 |
+----------------------+
1 row in set (0.00 sec)
mysql> select count(math) from exam_result;
+-------------+
| count(math) |
+-------------+
| 7 |
+-------------+
1.2 sum
统计英语成绩总分
mysql> select sum(english) from exam_result;
+--------------+
| sum(english) |
+--------------+
| 443 |
+--------------+
1 row in set (0.00 sec)
mysql> select sum(english) from exam_result where english<60;
+--------------+
| sum(english) |
+--------------+
| 131 |
+--------------+
1.3 avg
计算英语成绩的平均分
mysql> select sum(english)/count(*) from exam_result ;
+-----------------------+
| sum(english)/count(*) |
+-----------------------+
| 63.285714285714285 |
+-----------------------+
1 row in set (0.00 sec)
mysql> select avg(english) from exam_result;
+--------------------+
| avg(english) |
+--------------------+
| 63.285714285714285 |
+--------------------+
1 row in set (0.00 sec)
计算总分的平均分
mysql> select avg(english+math+chinese) from exam_result;
+---------------------------+
| avg(english+math+chinese) |
+---------------------------+
| 222 |
+---------------------------+
1.4 max 和 min
返回英语最高分
mysql> select max(english) from exam_result;
+--------------+
| max(english) |
+--------------+
| 90 |
+--------------+
1 row in set (0.00 sec)
返回 > 70 分以上的数学最低分
mysql> select min(math) from exam_result where math>70;
+-----------+
| min(math) |
+-----------+
| 73 |
+-----------+
1 row in set (0.00 sec)
2. group by
在select中使用group by 子句可以对指定列进行分组查询。
表结构如下
显示每个部门的平均工资和最高工资
mysql> select deptno,avg(sal) avgsal,max(sal) maxasl from emp group by deptno;
+--------+-------------+---------+
| deptno | avgsal | maxasl |
+--------+-------------+---------+
| 10 | 2916.666667 | 5000.00 |
| 20 | 2175.000000 | 3000.00 |
| 30 | 1566.666667 | 2850.00 |
+--------+