您的位置:首页 > 数据库 > Oracle

oracle分析函数row_number() over()使用

2011-05-10 17:47 706 查看
row_number() over ([partition by col1] order by col2) ) as 别名
表示根据col1分组,在分组内部根据 col2排序
而这个“别名”的值就表示每组内部排序后的顺序编号(组内连续的唯一的),[partition by col1] 可省略。

以Scott/tiger登陆,以emp表为例。

1、select deptno,ename,sal,
sum(sal) over (order by ename) 累计, --按姓名排序,并将薪水逐个累加
sum(sal) over () 总和 , -- 此处sum(sal) over () 等同于sum(sal),求薪水总和
100*round(sal/sum(sal) over (),4) "份额(%)" --求每个人的薪水占总额的比例,小数点后保留2位,括号和百分号为特殊符号,所以需要“”
from emp







2、select deptno,ename,sal,
sum(sal) over (partition by deptno order by ename) 部门连续求和,--partition by deptno先按部门分组,再按姓名排序,并将薪水逐个累加
sum(sal) over (partition by deptno) 部门总和, -- 每个部门的薪水总和
100*round(sal/sum(sal) over (partition by deptno),4) "部门份额(%)",--每个员工在各自部门的薪水比例
sum(sal) over (order by deptno,ename) 连续求和, --所有部门的薪水"连续"求和
sum(sal) over () 总和, -- 此处sum(sal) over () 等同于sum(sal),所有员工的薪水总和
100*round(sal/sum(sal) over (),4) "总份额(%)" --求每个人的薪水占总额的比例
from emp







3、select deptno,ename,sal,sum(sal) over (partition by deptno order by sal) dept_sum,--根据部门分组,再按部门内的个人薪水排序,逐个累加。
sum(sal) over (order by deptno,sal) sum --按部门排序,将薪水逐个累加。
from emp;







SQL> select * from
2 (select employees.*,row_number()over(order by emp_id) rowcount from employees)
3 where rowcount<=10;

DEPT_ID NAME EMP_ID ROWCOUNT
---------- -------------------- ---------- ----------
10 a 1001 1
20 c 1002 2
10 b 1003 3
20 d 1004 4
20 d 1005 5
30 e 1006 6
30 f 1007 7
40 g 1008 8
60 i 1009 9
50 j 1010 10

SQL> select * from
2 (select employees.*,row_number()over(partition by dept_id order by emp_id) rowcount from employees)
3 where rowcount<=3;

DEPT_ID NAME EMP_ID ROWCOUNT
---------- -------------------- ---------- ----------
10 a 1001 1
10 b 1003 2
20 c 1002 1
20 d 1004 2
20 d 1005 3
30 e 1006 1
30 f 1007 2
40 g 1008 1
40 h 1011 2
50 j 1010 1
50 k 1012 2

DEPT_ID NAME EMP_ID ROWCOUNT
---------- -------------------- ---------- ----------
60 i 1009 1

SQL> select * from
2 (select employees.*,row_number()over(partition by dept_id order by emp_id) rowcount from employees)
3 where rowcount<=10;

DEPT_ID NAME EMP_ID ROWCOUNT
---------- -------------------- ---------- ----------
10 a 1001 1
10 b 1003 2
20 c 1002 1
20 d 1004 2
20 d 1005 3
20 l 1013 4
30 e 1006 1
30 f 1007 2
40 g 1008 1
40 h 1011 2
50 j 1010 1

DEPT_ID NAME EMP_ID ROWCOUNT
---------- -------------------- ---------- ----------
50 k 1012 2
60 i 1009 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: