5
类聚集函数:
聚集函数用于对于一个集合中的数据进行处理,不是一行一行的数据
count统计行数、
sum
求和、
max
最大值、
min
最小值、
avg
平均值
计数
语法 count([all/distinct] 列名称
/*)
eg:获取总学生数
select count(*) from tb_student;
select count(1) from tb_student;
select count(distinct dept) from tb_student; -- 获取系的个数
mysql> select * from tb_student;
+----+--------+------+------+--------+
| id | name | age | sex | dept |
+----+--------+------+------+--------+
| 1 | 小熊 | 18 | 1 | 软工 |
| 2 | 小猴 | 16 | 0 | 计科 |
| 3 | 小猪 | 19 | 1 | 大数据 |
| 4 | 小猫 | 16 | 1 | 软工 |
| 5 | 小狗 | 16 | 1 | 软工 |
| 6 | 小兔 | 16 | 1 | NULL |
+----+--------+------+------+--------+
6 rows in set (0.00 sec)
select count(dept) from tb_student; -- 进行计数统计时,null不参与统计
eg:需要统计选修
1
号课程的学生人数
select count(*) from tb_choice where cid=1;
假设选择表中需要记录补考成绩,也就是意味着课程会有重复,则问题
1
:
primary key(cid,sid)
就是错误的,
学生编号
|
学生编号
|
成绩
|
1 | 3 | 45 |
1 | 3 | 75 |
由于出现重复计数,则选修人数统计出错
select count(distinct sid) from tb_choice where cid=1;
统计值:
用于数值类型的列,不要用于其他类型。max min sum avg
①max/min可以用于日期类型比较,最新的日期最大