分组查询GROUP BY
select * from student;
select * from student group by class;
在对数据进行分组的时候,SELECT后面必须是分组字段或者聚合函数
select class from student group by class;
按 class 列对 student 表分组,每组仅返回一个 class 值
select class, avg(age) from student group by class;
按 class 分组,计算每组学生的年龄平均值( AVG(age) ),并返回班级和对应平均年龄。
select gender, avg(age) avgAge from student group by gender;
给 avg(age)改名 avgAge 。
HAVING条件查询
WHERE是去数据表中查询符合条件的数据返回结果集
HAVING是去结果集中查询符合条件的数据,可以对分组之后查询到的结果进行筛选
select class, avg(age) from student group by class;
select class, avg(age)from student group by class where avg(age)<= 19;报错
select class, avg(age) from student group by class having avg(age)<= 19;
从结果集中筛选
select class, avg(age) avg from student group by class having avg <= 19;
--取别名