在where后面,不要出现聚合函数。
一般先执行where语句,在执行分组语句,最后执行聚合函数
聚集函数的使用
-- 将学生表中的所有数据复制到用户表
--(将查询的结果作为插入数据);
insert into test_user(name, email) select name,qq_mail from student:
常见的聚合函数
--例1:查询学生总数
count(*) --代表一行记录任意字段有值,就会统计在内
count(card) --代表只统计card字段的个数,如果有null值不会被统计
select count(*)from students;
select count(card)from students
--例2:查询女生的最大年龄
select max(age) from students where sex='女';
--例3:查询1班的最小年龄
select min(age) from students where class='1班';
--例4:查询北京学生的年龄总和
select sum(age) from students where hometown='北京';;
--例5:查询女生的平均年龄
select avg(age) from students where sex='女';
select count(distinct id) from exam_result;
select sum(math) from exam_result;
select sum(math) from exam_result where math < 70;
-- 统计数学成绩总分
SELECT SUM(math) FROM exam_result;
-- 不及格 < 60 的总分,没有结果,返回 NULL
SELECT SUM(math) FROM exam_result WHERE math < 60;
select AVG(math) from exam_result;
-- 统计平均总分
SELECT AVG(chinese + math + english) 平均总分 FROM exam_result;
select MAX(math) from exam_result;
-- 返回英语最高分
SELECT MAX(english) FROM exam_result;
-- 返回 > 70 分以上的数学最低分
SELECT MIN(math) FROM exam_result WHERE math > 70;
分组查询
--分组(group by)通常与聚合函数结合使用
--按服某个宁段分组后,再对每组数据分别进行统计
select max(age) as 最大年龄,min(age) 最小年龄, avg(age) 平均年龄 from stude;
select count(*) from students where class='1班';
select count(*) from students where class='3班' and age<18
--例1∶查询各种性别的人数
select sex , count(*) from students group by sex
--例2:查询各种年龄的人数
select age,count(*) from students group by age;
--查询各个班级学生的平均年龄、最大年龄、最小年龄
select class,avg(age),max(age),min(age) from students group by class;
--按闟多个字段分组,当一行记录的这多个字段都一样时被分在一组里面
select class,sex,count(*) from students group by class,sex;
--分组后过滤where 与having的区别
--作用一样但
--where是对from后面指定的表进行数据筹选,属于对原始数据的筛选
--having是对group by的结果进行筛选,having 必须用在group by 后
--例1:查询男生总人数
select count(*) from students where sex='男';
select sex,count(*) from students group by sex having sex='男";
分页查询
--例1:查询前3行学生信息
select * from students limit 0,3;
select * from students limit 4,4;
--按照排序后的顺序获取
select * from students order by age limit 0,3;
--要求每页显示3条
select count(*)from students
--12/3获取总页数
--第一页
select * from students limit 0,3; --3*(1-1)
--第二页
select * from students limit 3,3;-- 3+(2-1)
--第三页
select * from students limit 6,3 ;--3*(3-1)
--第四页
select * from students limit 9,3 ;--3*(4-1)
select * from students limit 7;--上面是下面的缩写
select * from students limit 0,7;