Oracle基礎知識———分組函數

第五章——分組函數
分組函數會對結果集中一組記錄計算一次,一組記錄返回一個結 果。

一、常用的分組函數
1.max([distinct]列|表達式) min([distinct]列|表達式):返回 的結果集中某列的最大值或最小值
例:查詢10部門中工資的最大值和最小值分別是多少
select max(salary),min(salary) from employees where department_id = 10;

2.sum([distinct]列|表達式):計算結果集中某列數值之和
例:計算10部門中員工的工資總數是多少
select sum(salary) from employees where department_id = 10;

3.avg([distinct]列|表達式):計算結果集中的某列數值的平均值
例:查詢10部門中員工的平均工資
select avg(salary) from employees where department_id;

4.count([distince]|列名):返回結果集中記錄的條數
例:查詢10不忙麼呢中員工的數量
select count(
) from employees where department_id = 10;

5.distince關鍵詞的用法
例:查詢employees表中的員工在幾個部門工作
select count(distince department_id) from employees;

6.group by 子句
1.分組函數通常和group by子句聯用,group by子句提供了一個分組的依據 group by子句中出現的列,可以不再select子句中出現
例:查詢employees表中各部門員工糉子對的最大值、最小值、總和和平均值
select department_id,max(salary),min(salary),sum(salary),avg(salary)
from employees
group by department_id;

2.select子句中出現的非分組函數列,一定要在group by子句中出現
例:查詢employees表中平均工資高於2000的部門編號個平均工資
select department_id,avg(salary)
from employees
–where avg(salary)>2000
group by department_id
having avg(salart)>2000

– having 子句:對分組函數的結果進行篩選,是SQL語句的執行順序所決定的
– where 子句中不能出現分組函數
例:查詢employees表中領導的員工編號以及下屬員工的數量
select manager_id,count(*) from employees group by manager_id having manager_id is not null;

發佈了42 篇原創文章 · 獲贊 703 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章