- 格式一:
- select 字段1,字段2 聚合函数 from 表名 group by字段1,字段2;
-
- 格式二:
- select 字段1,字段2 聚合函数 from 表名 where 条件 group by字段1,字段2;
- 例子
- -- 查询表中男女各有多少人数
- select count(sex),sex from students group by sex;

- -- 查询一班男女生数量
- select sex,count(*) from students where class ='1班' group by sex;

练习
- -- 查询表中各个年龄同学数量
- 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 ;
- 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;
- 语法
- select * from 表名 group by 字段 having 条件
-
- 例子:
- -- 用having查询男生总数
- select count(*) from students group by sex having sex ='男';
- -- 用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;
group by > having > order by > limit