oracle查询前几条数据的方法

在Oralce中实现select top N:由于Oracle不支持select top 语句,所以在oracle中经常是用order by 跟rownum的组合来实现select top n的查询。
方法1:

SELECT *
FROM (SELECT * FROM EMP ORDER BY SAL DESC)
WHERE ROWNUM <= 5 --抽取处记录数

方法2:分组排序语法:row_number() over(partition by 分组字段A,分组字段B,… order by 排序字段) RN_

SELECT *
FROM (SELECT A.EMPNO,
A.ENAME,
A.SAL,
ROW_NUMBER() OVER( /PARTITION BY EMPNO/ ORDER BY SAL DESC) AS RN_
FROM EMP A)
WHERE RN_ <= 5

附:取10-15条数据的方法
1、最接选择,利用分析函数row_number() over(partition by 分组字段A,分组字段B,… order by 排序字段) RN_

SELECT *
FROM (SELECT A.EMPNO,
A.ENAME,
A.SAL,
ROW_NUMBER() OVER( /PARTITION BY EMPNO/ ORDER BY SAL DESC) AS RN_
FROM EMP A)
WHERE RN_ BETWEEN 10 AND 15

2、使用rownum虚列

SELECT *
FROM (SELECT A.EMPNO, A.ENAME, A.SAL, ROWNUM AS RN
FROM (SELECT A.EMPNO, A.ENAME, A.SAL FROM EMP A ORDER BY SAL DESC) A)
WHERE RN BETWEEN 10 AND 15;

你可能感兴趣的:(oracle,oracle,数据库,top,ROWNUM,ROW_NUMBER,OVER)