一、分组
group by
- 按照字段分组,相同字段数据被放到同一个组内
- 分组目的是为了配合聚合函数使用
sql
格式一:
select 字段1,字段2 聚合函数 from 表名 group by字段1,字段2;
格式二:
select 字段1,字段2 聚合函数 from 表名 where 条件 group by字段1,字段2;
sql
例子
-- 查询表中男女各有多少人数
select count(sex),sex from students group by sex;
sql
-- 查询一班男女生数量
select sex,count(*) from students where class ='1班' group by sex;
练习
sql
-- 查询表中各个年龄同学数量
select age,count(*) from students group by age;
-- 查询表中2班和4班女生各有多少人数
select class,count(sex),sex from students where
(class = '2班' or class = '4班') and sex = '女'group by class;
-- 数据分组,统计统计各个班级学生总数,最大、最小、平均年龄,
select class,count(*),max(age),min(age),avg(age)
from students group by class ;
where&group by &order by 同时出现使用顺序
- where > group by > order by
sql
select 字段, 聚合函数 from 表名
where 条件 group by 字段 order by 字段;
/* 例子
数据分组,统计统计各个班级学生总数,最大、最小、平均年龄*/
select class,count(*),max(age),min(age),avg(age)
from students
where not class = '3班' group by class order By class desc;
二、分组后进行筛选
having与where区别
- where条件 是先筛选统计,在统计结果中分组
- having 是先分组统计,在统计结果中筛选
- 必须出现 group by 后面
sql
语法
select * from 表名 group by 字段 having 条件
例子:
-- 用having查询男生总数
select count(*) from students group by sex having sex ='男';
having配合聚合函数使用
- where后面不能使用聚合函数,having后面能使用聚合函数
sql
-- 用having班级人数大于3人的班级
select class from students group by class having count(*)> 3;
-- 班级总人数大于2的人班级名称、班级对应人数
select class,count(*) from students
group by class having count(*)> 2;
-- 查询平均年龄大于30班级名称、班级总人数
select class,count(*) from students
group by class having avg(age)> 30;
-- 查询4班和2班男女人数各多少
-- 方式一:
select class,sex,count(*) from students
GROUP BY class, sex having class = '4班' or class = '2班';
-- 方式二:
select class,sex,count(*) from students
where class = '4班' or class = '2班' group by class,sex;