今开发人员人员需要查找介于10-21的数据:
SELECT *
FROM (SELECT FROM WHERE GROUP BY ORDER BY desc) ta
WHERE ta.rownum > 10 AND ta.rownum < 21
不得结果,事实上:
rownum是一个总是从1开始的伪列,Oracle 认为这种条件(不能使用>)不成立,查不到记录.但可以使用相减的方法来实现(minus操作,速度会受影响)
select * from (select * from where group by /order by ) where rownum<21
minus
select *............................where rownum<10
另外可以参考网上一篇文章:含义解释:
1、rownum是oracle系统顺序分配为从查询返回的行的编号,返回的第一行分配的是1,第二行是2,
依此类推,这个伪字段可以用于限制查询返回的总行数。
2、rownum不能以任何基表的名称作为前缀。
使用方法:
现有一个商品销售表sale,表结构为:
month char(6) --月份
sell number(10,2) --月销售金额
create table sale (month char(6),sell number);
insert into sale values('',1000);
insert into sale values('',1100);
insert into sale values('',1200);
insert into sale values('',1300);
insert into sale values('',1400);
insert into sale values('',1500);
insert into sale values('',1600);
insert into sale values('',1100);
insert into sale values('',1200);
insert into sale values('',1300);
insert into sale values('',1000);
commit;
SQL> select rownum,month,sell from sale where rownum=1;(可以用在限制返回记录条数的地方,保证不出错,如:隐式游标)
ROWNUM MONTH SELL
--------- ------ ---------
1 1000
SQL> select rownum,month,sell from sale where rownum=2;(1以上都查不到记录)
没有查到记录
ROWNUM MONTH SELL
--------- ------ ---------
1 1000
2 1100
3 1200
如何用rownum实现大于、小于逻辑?(返回rownum在4—10之间的数据)(minus操作,速度会受影响)
SQL> select rownum,month,sell from sale where rownum<10
2 minus
3 select rownum,month,sell from sale where rownum<5;
ROWNUM MONTH SELL
--------- ------ ---------
5 1400
6 1500
7 1600
8 1100
9 1200
ROWNUM MONTH SELL
--------- ------ ---------
1 1000
2 1100
3 1200
4 1300
5 1400
6 1500
7 1600
11 1000
8 1100
9 1200
10 1300
查询到11记录.
可以发现,rownum并没有实现我们的意图,系统是按照记录入库时的顺序给记录排的号,rowid也是顺序分配的
SQL> select rowid,rownum,month,sell from sale order by rowid;
ROWID ROWNUM MONTH SELL
------------------ --------- ------ ---------
000000E4.0000.0002 1 1000
000000E4.0001.0002 2 1100
000000E4.0002.0002 3 1200
000000E4.0003.0002 4 1300
000000E4.0004.0002 5 1400
000000E4.0005.0002 6 1500
000000E4.0006.0002 7 1600
000000E4.0007.0002 8 1100
000000E4.0008.0002 9 1200
000000E4.0009.0002 10 1300
000000E4.000A.0002 11 1000
查询到11记录.
ROWNUM MONTH SELL
--------- ------ ---------
1 1000
2 1100
3 1200
4 1300
5 1400
6 1500
7 1600
8 1000
9 1100
10 1200
11 1300
ROWNUM MONTH SELL
--------- ------ ---------
1 1000
2 1000
3 1100
4 1100
5 1200
6 1200
7 1300
8 1300
9 1400
10 1500
11 1600
查询到11记录.
利用以上方法,如在打印报表时,想在查出的数据中自动加上行号,就可以利用rownum。
返回第5—9条纪录,按月份排序
SQL> select * from (select rownum row_id ,month,sell
2 from (select month,sell from sale group by month,sell))
3 where row_id between 5 and 9;
ROW_ID MONTH SELL
---------- ------ ----------
5 1400
6 1500
7 1600
8 1000
9 1100
转载于:http://blog.itpub.net//viewspace-66225/

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/27535.html