分組查詢主要涉及到兩個(gè)子句,分別是:group by和having。
● 取得每個(gè)工作崗位的工資合計(jì),要求顯示崗位名稱和工資合計(jì)
select job, sum(sal) from emp group by job;
如果使用了order by,order by必須放到group by后面
● 按照工作崗位和部門編碼分組,取得的工資合計(jì)
1、原始數(shù)據(jù)
2、分組語(yǔ)句
select job,deptno,sum(sal) from emp group by job,deptno;
mysql> select empno,deptno,avg(sal) from emp group by deptno;
+-------+--------+-------------+
| empno | deptno | avg(sal) |
+-------+--------+-------------+
| 7782 | 10 | 2916.666667 |
| 7369 | 20 | 2175.000000 |
| 7499 | 30 | 1566.666667 |
+-------+--------+-------------+
以上SQL語(yǔ)句在Oracle數(shù)據(jù)庫(kù)中無(wú)法執(zhí)行,執(zhí)行報(bào)錯(cuò)。
以上SQL語(yǔ)句在Mysql數(shù)據(jù)庫(kù)中可以執(zhí)行,但是執(zhí)行結(jié)果矛盾。
在SQL語(yǔ)句中若有g(shù)roup by 語(yǔ)句,那么在select語(yǔ)句后面只能跟分組函數(shù)+參與分組的字段。
如果想對(duì)分組數(shù)據(jù)再進(jìn)行過(guò)濾需要使用having子句;
取得每個(gè)崗位的平均工資大于2000;
select job, avg(sal) from emp group by job having avg(sal) >2000;
分組函數(shù)的執(zhí)行順序:
● 根據(jù)條件查詢數(shù)據(jù)
● 分組
● 采用having過(guò)濾,取得正確的數(shù)據(jù)
一個(gè)完整的select語(yǔ)句格式如下:
select 字段
from 表名
where …….
group by ……..
having …….(就是為了過(guò)濾分組后的數(shù)據(jù)而存在的—不可以單獨(dú)的出現(xiàn))
order by ……..
以上語(yǔ)句的執(zhí)行順序
● 首先執(zhí)行where語(yǔ)句過(guò)濾原始數(shù)據(jù)
● 執(zhí)行g(shù)roup by進(jìn)行分組
● 執(zhí)行having對(duì)分組數(shù)據(jù)進(jìn)行操作
● 執(zhí)行select選出數(shù)據(jù)
● 執(zhí)行order by排序
原則:能在where中過(guò)濾的數(shù)據(jù),盡量在where中過(guò)濾,效率較高。having的過(guò)濾是專門對(duì)分組之后的數(shù)據(jù)進(jìn)行過(guò)濾的。