mysql 中 group by 用法

一、數據結構
#建立表staff, 3個部門的信息
mysql 中 group by 用法
二、建立表、插入信息mysql

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 用法

相關文章
相關標籤/搜索