1. 程式人生 > 其它 >009、分組查詢(group by)

009、分組查詢(group by)

分組查詢(group by)

分組查詢 分組查詢主要涉及到兩個子句,分別是:group by 和 having,having不可單獨出現,需要和group by 一起使用。
# -------------------------9、分組查詢 -------------------------
# 取得每個工作崗位的工資合計,要求顯示崗位名稱和工資合計。
select * from emp;
select job, sum(sal) from emp group by job;

# 按照工作崗位和部門編碼分組,取得的工資合計
# 在 SQL 語句中若有 group by 語句,那麼在 select 語句後面只能跟分組函式+參與分組的欄位。
select deptno, job, sum(sal) from emp group by deptno, job; # 取得每個崗位的平均工資大於 2000 # 有group by語句,後面不能有where select job, avg(sal) from emp group by job having avg(sal)>2000;
select 語句總結 一個完整的 select 語句格式如下:   select 欄位   from 表名   where …….   group by ……..   having …….(就是為了過濾分組後的資料而存在的—不可以單獨的出現)   order by ……..
以上語句的執行順序   1. 首先執行 where 語句過濾原始資料   2. 執行 group by 進行分組   3. 執行 having 對分組資料進行操作   4. 執行 select 選出資料   5. 執行 order by 排序 原則:能在 where 中過濾的資料,儘量在 where 中過濾,效率較高。having 的過濾是專門對分組之後的資料進行過濾 的。