按照必定標準把數據分紅若干部分sql
from 表名 where 條件 group by 分組標準 (group標準的要寫在where以後,沒有where寫在from以後)
語句:select dept_id,count(id) from s_emp group by dept_id;
select dept_id, count(id) from s_emp group by dept_id having count(id)>2 order by dept_id desc;
select dept_id, avg(salary) from s_emp group by dept_id having avg(salary)>1300;
在分組語句中,select後的字段要麼是分組標準,要麼是通過合適組函數處理過的內容函數
select dept_id, avg(salary), name from s_emp e, s_dept d where dept_id=d.id group by dept_id, name having avb(salary)>1300;
(存在一些問題)匹配顯示次數問題3d
因此用組函數,由於組函數只會有一個結果, 若是用count:blog
select dept_id, avg(salary), count(name) from s_emp e, s_dept d where dept_id=d.id group by dept_id having avg(salary)>1300;
若是用max:排序
select dept_id, avg(salary), max(name) from s_emp e, s_dept d where dept_id=d.id group by dept_id having avg(salary)>1300;
由於可能會有的部門沒有對應部門名,數據會丟失,則要所有顯示部門表的內容,因此還要加上外鏈接。class
select dept_id, avg(salary), count(name) from s_emp e, s_dept d where dept_id=d.id(+) group by dept_id having avg(aslary)>1300;
(1)from 先找到要操做的表select
(2)where 會有過濾條件sql語句
(3)group by 分組確定在having以前語法
(4)having 對組數據進行過濾 經過下面舉例的別名能夠肯定having和select的執行順序im
(5)select 查詢輸出(語法規則要求select寫前面)
(6)order by 永遠在最後
select dept_id, count(id) ac from s_emp group by dept_id having count(id)>2 order by ac;