[Oracle]高效的SQL语句之分析函数(一)--sum()

本系列文章导航

[Oracle]高效的SQL语句之分析函数(一)--sum()

[Oracle]高效的SQL语句之分析函数(二)--max()

[Oracle]高效的SQL语句之分析函数(三)--row_number() /rank()/dense_rank()

[Oracle]高效的SQL语句之分析函数(四)--lag()/lead()

实际应用中我们可以通过sum()统计出组中的总计或者是累加值,具体示例如下:

1.创建演示表

create table emp
as
select * from scott.emp;

alter table emp
add constraint emp_pk
primary key (empno);

create table dept
as
select * from scott.dept;

alter table dept
add constraint dept_pk
primary key (deptno);


2. sum()语句如下:

select deptno,
ename,
sal,
  
-- 按照部门薪水累加(orderby改变了分析函数的作用,只工作在当前行和前一行,而不是所有行)
sum (sal) over (partition by deptno order by sal)CumDeptTot,
sum (sal) over (partition by deptno)SalByDept, -- 统计一个部门的薪水
sum (sal) over ( order by deptno,sal)CumTot, -- 所有雇员的薪水一行一行的累加
sum (sal) over ()TotSal -- 统计总薪水
from emp
order by deptno,sal

3. 结果如下:

10MILLER1300.0013008750130029025
10CLARK2450.0037508750375029025
10KING5000.0087508750875029025
20SMITH800.0080010875955029025
20ADAMS1100.001900108751065029025
20JONES2975.004875108751362529025
20SCOTT3000.0010875108751962529025
20FORD3000.0010875108751962529025
30JAMES950.0095094002057529025
30WARD1250.00345094002307529025
30MARTIN1250.00345094002307529025
30TURNER1500.00495094002457529025
30ALLEN1600.00655094002617529025
30BLAKE2850.00940094002902529025


博文来源:http://blog.csdn.net/huanghui22/archive/2007/05/03/1595157.aspx

你可能感兴趣的:(oracle)