深入学习之mysql(四)聚合函数
聚合函数:COUNT统计记录的条数、SUM求和函数、AVG求平均值、MAX求最大值、MIN求最小值
一、COUNT练习:
1、统计学校一共有多少个学生:
mysql> SELECT COUNT(*) AS 'Total' FROM t_student;
+-------+
| Total |
+-------+
| 13 |
+-------+
1 row in set (0.01 sec)
2、统计每个年级各有多少学生:
mysql> SELECT COUNT(*) AS 'Total',gradeName FROM t_student GROUP BY gradeName;
+-------+-----------+
| Total | gradeName |
+-------+-----------+
| 6 | 一年级 |
| 3 | 三年级 |
| 4 | 二年级 |
+-------+-----------+
3 rows in set (0.00 sec)
3、在2的基础上添加学生总数:
mysql> select IFNULL(gradeName,'学生总数'),COUNT(*) AS Total from t_student Group By gradeName with Rollup;
+----------------------------------+-------+
| IFNULL(gradeName,'学生总数') | Total |
+----------------------------------+-------+
| 一年级 | 6 |
| 三年级 | 3 |
| 二年级 | 4 |
| 学生总数 | 13 |
+----------------------------------+-------+
4 rows in set (0.00 sec)
二、SUM求和函数:
1、查询所有学生的年龄总和:
mysql> SELECT SUM(age) AS '年龄总和' FROM t_student;
+--------------+
| 年龄总和 |
+--------------+
| 295 |
+--------------+
1 row in set (0.00 sec)
2、在1的基础上添加一班级为单位进行分组
mysql> SELECT SUM(age) AS '年龄总和',IFNULL(gradeName,'年级总年龄') AS '年级' FROM t_student GROUP BY gradeName WITH ROLLUP;
+--------------+-----------------+
| 年龄总和 | 年级 |
+--------------+-----------------+
| 135 | 一年级 |
| 66 | 三年级 |
| 94 | 二年级 |
| 295 | 年级总年龄 |
+--------------+-----------------+
4 rows in set (0.00 sec)
三、AVG平均值函数
1、查看全年级的平均年龄
mysql> SELECT AVG(AGE) AS '平均年龄' FROM t_student;
+--------------+
| 平均年龄 |
+--------------+
| 22.6923 |
+--------------+
1 row in set (0.00 sec)
2、在1的基础上进行按班级分组并在分组后统计总的平均年龄
mysql> SELECT AVG(AGE) AS '平均年龄',IFNULL(gradeName,'年级平均年龄') AS '年级平均年龄' FROM t_student GROUP BY gradeName WITH ROLLUP;
+--------------+--------------------+
| 平均年龄 | 年级平均年龄 |
+--------------+--------------------+
| 22.5000 | 一年级 |
| 22.0000 | 三年级 |
| 23.5000 | 二年级 |
| 22.6923 | 年级平均年龄 |
+--------------+--------------------+
4 rows in set (0.00 sec)
四、MAX求最大值:
1、查找每个年级的最大年龄并以年级进行排序:
mysql> SELECT MAX(age) AS '年龄最大',gradeName AS '年级' FROM t_student GROUP BY gradeName ;
+--------------+-----------+
| 年龄最大 | 年级 |
+--------------+-----------+
| 23 | 一年级 |
| 23 | 三年级 |
| 26 | 二年级 |
+--------------+-----------+
3 rows in set (0.00 sec)
五、MIN求最小值
1、查询每个年级中的最小年龄,并以年级进行排序:
mysql> SELECT MIN(age) AS'年龄最小',gradeName AS '年级' FROM t_student GROUP BY gradeName;
+--------------+-----------+
| 年龄最小 | 年级 |
+--------------+-----------+
| 21 | 一年级 |
| 20 | 三年级 |
| 21 | 二年级 |
+--------------+-----------+
3 rows in set (0.00 sec)
笃信仁厚,慎思勤勉