Oracle 分組函數
分組函數作用于一組數據,并對一組函數返回一個值。
組函數類型:
avg,count,max,min,sum
可以對數值型數據使用avg和sum函數。
select avg(salary),min(salary),max(salary),sum(salary) from employees where job_id like '%REP%';
avg(平均值)和sum(合計)函數:
可以對任意數據類型的數據使用 min和 max函數(包括日期)。
select min(hire_date),max(hire_date) from employees
count(*)返回表中記錄總數,適用于任意數據類型。
select count(*) from employees where department_id = 50;
count (expr) 返回expr不為空的記錄總數。
select count (commission_pct) from employees where department_id = 50;
組函數忽略空值:
select avg(commission_pct) from employees;
·
NVL函數使分組函數無法忽略空值:
select avg(nvl(commission_pct,0)) from employees;
count (distinct expr)返回expr非空且不重復的記錄總數
select count(distinct department_id) from employees;
可以使用group by子句將表中的數據分成若干組,在select列表中所有未包含在組函數中的列都應該包含在 group by子句中。
select department_id,avg(salary) from employees group by department_id;
包含在 group by 子句中的列不必包含在select列表中:
select avg(salary) from employees group by department_id;
在group by 子句中包含多個列:
select department_id,job_id,sum(salary) from employees group by department_id,job_id;
非法使用組函數:所有包含于select列表中,而未包含于組函數中的列都
必須包含于 GROUP BY 子句中。
如下:
select department_id,count(last_name) from employees;
非法使用組函數:
? 不能在where子句中使用組函數。
? 可以在having子句中使用組函數。
如下:
select department_id,avg(saslary) from employees where avg(salary)>8000 group by department_id;
過濾分組:having 子句
- 行已經被分組。
- 使用了組函數。
- 滿足having子句中條件的分組將被顯示。
select department_id,max(salary) from employees group by department_id having max(salary)>10000;
嵌套組函數:
select max(avg(salary)) from employees group by department_id;