为了快速得到统计数据,经常会用到如下5个聚合函数
注:聚合函数不能在where后面的条件中使用
一、count总记录数
count(*)表示计算总记录数,括号中写 * 与字段名,结果是相同的
例1:查询学生总数(学生总数就是students表中记录的总数)
select count(*) from students;
例2:查询性别sex为’女’的学生总数
select count(*) from students where sex='女';
二、max最大值
max(字段)表示求此字段的最大值
例3:查询最大age年龄
select max(age) from students;
例4:查询性别为‘女’的最大age年龄
SELECT max(age) from students where sex='女';
- 聚合函数不能在where后面的条件中使用
例5:错误!!!不能用如下语句查询年龄最大学生的信息
select * from students where age=max(age);
- 聚合函数不能与普通字段同时出现在查询结果中
例6:错误!!!不能用如下语句查询年龄最大学生的信息
select name,max(age) from students;
三、min最小值
min(字段)表示求此字段的最小值
例7:查询学生最小age年龄
select min(age) from students;
例8:查询class班级为’1班’的最小age年龄
select min(age) from students where class='1班';
四、sum求和
sum(字段)表示求此字段的和
例9:查询age年龄的总和
select sum(age) from students;
例10:查询hometown为‘北京’的学生age年龄的总和
select sum(age) from students where hometown='北京';
五、avg平均值
avg(字段)表示求此字段的平均值
例11:查询学生的平均年龄
select avg(age) from students;
例12:查询sex性别为‘男’的平均年龄
select avg(age) from students where sex='男';
-- 练习1:查询所有学生的最大年龄、最小年龄、平均年龄;
select max(age),min(age),avg(age) from students;
-- 练习2:查询’1班’共有多少个学生;
select count(*) from students where class='1班';
-- 练习3:查询’3班’中年龄小于30岁的同学有几个;
select count(*) from students where class='3班' and age<30;