I have to get second five (6-10) best salaries records from sorted table using ROWNUM.
Using ROWNUM is necessary.
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. 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. For example, this query returns no rows:SELECT * FROM employees WHERE ROWNUM > 1;
But, more importantly, you are using Oracle 12C. So, use fetch first
instead of rownum
. This has multiple advantages. Besides being standard SQL, you don't need a subquery:
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.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.