1、数据结构
#创建表staff, 3个部门的信息
mysql 中 group by 用法
2、创建表、插入信息

CREATE TABLE `tb_staff` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `depart` varchar(32) DEFAULT NULL,
  `name` varchar(32) NOT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);
insert into tb_staff values(1,'tech','li1',30);
insert into tb_staff values(2,'hr','li2',24);
insert into tb_staff values(3,'tech','li3',35);
insert into tb_staff values(4,'tech','li4',35);
insert into tb_staff values(5,'tech','li5',40);
insert into tb_staff values(6,'hr','li6',26);
insert into tb_staff values(7,'hr','li7',28);
insert into tb_staff values(8,'hr','li8',29);
insert into tb_staff values(9,'ops','li9',32);
insert into tb_staff values(10,'ops','li10',32);
insert into tb_staff values(11,'ops','li11',43);
insert into tb_staff values(12,'ops','li12',41);
insert into tb_staff values(13,'hr','li13',40);
insert into tb_staff values(14,'hr','li14',24);
查询,hr部门6个人,tech部门4个人,ops部门4个人

mysql 中 group by 用法

使用group by ,报错如下

mysql 中 group by 用法

修改my.cnf文件,然后systemctl restart mysqld
vim /etc/my.cnf
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
group by  xxx : 根据后面字段进行分组,值相同则为一组,经常与聚合函数结合使用 count(),sum(),avg(),max(),min()
where having 与 group by 结合,where 子句在聚合前执行,having 在聚合后对组结果进行筛选
1)使用goup by 统计每个部门的总人数
select depart,count(name) from tb_staff group by depart;

mysql 中 group by 用法

2) 统计部门里年纪最大的员工
select depart as "部门",name as "名字",max(age) as "最大年龄" from tb_staff group by depart

mysql 中 group by 用法
mysql 中 group by 用法

3)统计部门中大于30岁的人数,与where 子名结合使用。 order by 默认升序
select id as count_head,depart,name from tb_staff where age > '30' group by depart order by id;

mysql 中 group by 用法

4)统计部门中平均年龄大于35岁的部门
select depart,avg(age) from tb_staff group by depart having avg(age) > 35;

mysql 中 group by 用法