明确对于rownum 来说 它是oracle 系统顺序分配为从查询返回的行的编号,返回的第一行分配的是1,第二行是二,以此类推,这个为字段可以用于限制查询的返回的总行数,因为rownum总是从1开始,但是1以上的自然数在rownum 做等于判断时都认为是false 条件,所以无法查到 rownum=n (n》1的自然数),所以查找第二行以后的记录可以用子查询方法来解决,给子查询中的rownum取别名;对于小于某个值的情况两种方法都差不多,但是对于某个不等于一的值或者求某个值到某个值之间的情况,用row_number() 别名获得排名 ,比用rownum伪列要简单方便的多;因为伪列总是从一开始查找;
具体用法和区别参见以下代码;
--取出工资最高的前5位
select empno,ename,sal,rownum from emp;
select * from (select * from emp order by sal desc) where rownum<=5;
select * from (select ename,sal,row_number() over(order by sal desc) as num from emp) where num<=5;
select * from (select ename,sal,row_number() over(order by sal desc) from emp) where rownum<=5
--工资的前3名
select * from emp where sal >=any(select * from (select sal from emp order by sal desc) where rownum<=3);
select * from(select * from emp order by sal desc) where rownum <4;
select * from (select ename,sal,empno,deptno ,row_number() over (order by sal desc) from emp) where rownum<4;
select * from (select ename,sal,empno,deptno ,row_number() over (order by sal desc) as num from emp) where num<4
--按照工资排序,取出第6名到第10名
--使用伪列获得
select * from (select ename,sal,rownum r from (select * from emp order by sal desc) where rownum<=10) where r>5;
--使用排名函数获得
select * from (select ename,sal,row_number() over(order by sal desc) as num from emp) where num>5 and num<=10;
------- 按工资从高到低获得工资排名第四的员工
select * from (select ename,sal,row_number() over(order by sal desc) as num from emp) where num=4;
select * from (select ename,sal,rownum r from (select * from emp order by sal desc) where rownum<=4) where r=4;
具体用法和区别参见以下代码;
--取出工资最高的前5位
select empno,ename,sal,rownum from emp;
select * from (select * from emp order by sal desc) where rownum<=5;
select * from (select ename,sal,row_number() over(order by sal desc) as num from emp) where num<=5;
select * from (select ename,sal,row_number() over(order by sal desc) from emp) where rownum<=5
--工资的前3名
select * from emp where sal >=any(select * from (select sal from emp order by sal desc) where rownum<=3);
select * from(select * from emp order by sal desc) where rownum <4;
select * from (select ename,sal,empno,deptno ,row_number() over (order by sal desc) from emp) where rownum<4;
select * from (select ename,sal,empno,deptno ,row_number() over (order by sal desc) as num from emp) where num<4
--按照工资排序,取出第6名到第10名
--使用伪列获得
select * from (select ename,sal,rownum r from (select * from emp order by sal desc) where rownum<=10) where r>5;
--使用排名函数获得
select * from (select ename,sal,row_number() over(order by sal desc) as num from emp) where num>5 and num<=10;
------- 按工资从高到低获得工资排名第四的员工
select * from (select ename,sal,row_number() over(order by sal desc) as num from emp) where num=4;
select * from (select ename,sal,rownum r from (select * from emp order by sal desc) where rownum<=4) where r=4;