日期:2014-05-16  浏览次数:20524 次

Oracle中over函数的使用示例

转自?http://www.cnblogs.com/umen/archive/2011/04/11/2012136.html

?

?

Oracle over函数

?

SQL code:?

sql over的作用及用法
RANK ( ) OVER ( [query_partition_clause] order_by_clause )
DENSE_RANK ( ) OVER ( [query_partition_clause] order_by_clause )
可实现按指定的字段分组排序,对于相同分组字段的结果集进行排序,
其中PARTITION BY 为分组字段,ORDER BY 指定排序字段


over不能单独使用,要和分析函数:rank(),dense_rank(),row_number()等一起使用。
其参数:over(partition by columnname1 order by columnname2)
含义:按columname1指定的字段进行分组排序,或者说按字段columnname1的值进行分组排序。
例如:employees表中,有两个部门的记录:department_id =10和20
select department_id,rank() over(partition by department_id order by salary) from employees就是指在部门10中进行薪水的排名,在部门20中进行薪水排名。如果是partition by org_id,则是在整个公司内进行排名。


SQL code:?
WITH
OBJ AS(
SELECT
name, type

?

目的:以oracle自带的scott模式为测试环境,主要通过试验体会分析函数的用法。

类似 sum(...) over ... 的使用


1.原表信息:

SQL> break on deptno skip 1 -- 为效果更明显,把不同部门的数据隔段显示。
SQL> select deptno,ename,sal
2 from emp
3 order by deptno;

??? DEPTNO ENAME???????????? SAL
---------- ---------- ----------
??????? 10 CLARK??????????? 2450
?????????? KING???????????? 5000
?????????? MILLER?????????? 1300

??????? 20 SMITH???????????? 800
?????????? ADAMS??????????? 1100
?????????? FORD???????????? 3000
?????????? SCOTT??????????? 3000
?????????? JONES??????????? 2975

??????? 30 ALLEN??????????? 1600
?????????? BLAKE??????????? 2850
?????????? MARTIN?????????? 1250
?????????? JAMES???????????? 950
?????????? TURNER?????????? 1500
?????????? WARD???????????? 1250


已选择14行。



2.先来一个简单的,注意over(...)条件的不同,
使用 sum(sal) over (order by ename)... 查询员工的薪水“连续”求和,
注意over (order by ename)如果没有order by 子句,求和就不是“连续”的,
放在一起,体会一下不同之处:

SQL> break on '' -- 取消数据分段显示
SQL> select deptno,ename,sal,
2 sum(sal) over (order by ename) 连续求和,
3 sum(sal) over () 总和,????????????????? -- 此处sum(sal) over () 等同于sum(sal)
4 100*round(sal/sum(sal) over (),4) "份额(%)"
5 from emp
6 /

??? DEPTNO ENAME???????????? SAL?? 连续求和?????? 总和??? 份额(%)
---------- ---------- ---------- ---------- ---------- ----------
??????? 20 ADAMS??????????? 1100?????? 1100????? 29025?????? 3.79
??????? 30 ALLEN??????????? 1600?????? 2700????? 29025?????? 5.51
??????? 30 BLAKE??????????? 2850?????? 5550????? 29025?????? 9.82
??????? 10 CLARK??????????? 2450?????? 8000????? 29025?????? 8.44
??????? 20 FORD???????????? 3000????? 11000????? 29025????? 10.34
??????? 30 JAMES???????????? 950????? 11950????? 29025?????? 3.27
??????? 20 JONES??????????? 2975????? 14925????? 29025????? 10.25
??????? 10 KING???????????? 5000????? 19925????? 29025????? 17.23
??????? 30 MARTIN?????????? 1250????? 21175????? 29025?????? 4.31
??????? 10 MILLER?????????? 1300????? 22475????? 29025?????? 4.48
??????? 20 SCOTT??????????? 3000????? 25475????? 29025????? 10.34
??????? 20 SMITH???????????? 800????? 26275????? 29025?????? 2.76
??????? 30 TURNER?????????? 1500????? 27775????? 29025?????? 5.17
??????? 30 WARD???????????? 1250????? 29025????? 2