分組查詢:使用 group by 來設置分組,把該列具有相同值的多條記錄當成一組記錄來處理,然后只會輸出一條記錄,得到的結果會默認使用升序的方式進行排列。
規則:
(1)如果使用了分組函數,或者是 group by 語句,當他出現在 select 列表中的字段,要么出現在組合函數中,要么出現在 group by 子句中,否則會報錯。
(2)group by 子句的字段可以不用出現在 select 列表中。
(3)使用組函數可以不使用 group by 子句,此時所有的查詢結果作為一組。
-- 首先,查看emp 表中的所有數據。
select * from scott.emp;
-- 在員工表中,按照部門來分組。
select deptno from scott.emp group by deptno;
-- 在員工表中,查詢每個部門的編號,員工數,總工資,平均獎金
select deptno, count(*), sum(sal), avg(sal)
from scott.emp group by deptno;
-- 在分組的時候,有時候需要進行進一步的過濾,可以使用 having 子句
-- having 是指“擁有xxx”的意思,也就是跟着一個條件,可以進行過濾篩選。
select deptno, count(*), sum(sal), avg(sal)
from scott.emp
group by deptno;
select deptno, count(*), sum(sal), avg(sal)
from scott.emp
group by deptno
having sum(sal) > 9000;
-- having 和 where 區別:
-- 1. 都是作為條件過濾。
-- 2. where 是在分組之前使用的,having 是在分組之后使用的,參照物是 group by
-- 3. where 子句中不能使用組函數(聚合函數),但 having 可以
升序排序:order by ...ASC(放在最后,對結果集進行排序)
降序排序:order by ...DESC(放在最后,對結果集進行排序)
-- 關鍵字的使用順序
select、from、where、group by、having、order by