[英]ORACLE 12C - SELECT query using ROWNUM
I have to get second five (6-10) best salaries records from sorted table using ROWNUM. 我必须使用ROWNUM从排序表中获取后五(6-10)个最佳薪水记录。
Using ROWNUM is necessary. 必须使用ROWNUM。
When I execute query: 当我执行查询时:
SELECT ROWNUM AS position, name, salary
FROM (SELECT name, salary
FROM employees
ORDER BY salary DESC)
WHERE ROWNUM <= 10;
I get a first 10 best records. 我获得前十项最佳记录。
And now when I try execute query: 现在,当我尝试执行查询时:
SELECT ROWNUM AS position, name, salary
FROM (SELECT name, salary
FROM employees
ORDER BY salary DESC)
WHERE ROWNUM >= 6 AND ROWNUM <= 10;
I get a empty table. 我有一张空桌子。 Why doesn't it work? 为什么不起作用?
As explained in the documentation , rownum
is evaluated as the rows are fetched. 如文档中所述,在提取行时会评估rownum
。 If you never fetch the first row, you never get to the second. 如果您从未获取第一行,那么您将永远不会到达第二行。 Hence, no rows are fetched: 因此,不会获取任何行:
Conditions testing for
ROWNUM
values greater than a positive integer are always false.ROWNUM
值大于正整数的条件测试始终为false。 For example, this query returns no rows: 例如,此查询不返回任何行:SELECT * FROM employees WHERE ROWNUM > 1;
But, more importantly, you are using Oracle 12C. 但是,更重要的是,您正在使用Oracle 12C。 So, use fetch first
instead of rownum
. 因此, fetch first
使用fetch first
而不是rownum
。 This has multiple advantages. 这具有多个优点。 Besides being standard SQL, you don't need a subquery: 除了作为标准SQL外,您不需要子查询:
SELECT name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 10 ROWS ONLY;
And for your second: 第二点:
SELECT name, salary
FROM employees
ORDER BY salary DESC
OFFSET 5 ROWS
FETCH FIRST 5 ROWS ONLY;
I write in queston that using ROWNUM is necessary, because it's academic task. 我在问题中写道,使用ROWNUM是必要的,因为这是学术任务。
In such a case use a subquery 在这种情况下,请使用子查询
SELECT name, salary
FROM (
SELECT name, salary, ROWNUM as my_rownum
FROM employees
ORDER BY salary DESC
)
WHERE my_rownum BETWEEN 6 AND 10
您可以使用以下查询并尝试...。
SELECT name,salary from ( SELECT name,salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rn from employees ) where rn between 6 and 10;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.