问题
I have HR oracle schema and in that, I want to display all the fields of employees who have a 3rd highest salary.
Here is what I have written so far but it does not return anything.
select * from (
select * from HR.EMPLOYEES
order by HR.EMPLOYEES.SALARY DESC)
where rownum=3
I want to get this result without using any functions like dense_rank() etc. Want to keep the query simple. But if someone can use analytic function and can explain its working then I can get the idea of its use so far I don't understand the use of functions like dense_rank(). Any idea of what I am missing in my query?
回答1:
rownum = 3
won't work because rownum
is applied to the generated resultset. The first row in a result set always has rownum = 1
. No resultset can match rownum = 3
so you get no rows back.
The way to do this is with an analytic function like rank()
, dense_rank()
or row_number()
.
select * from
( select emp.*
, dense_rank() over (order by salary desc) rn
from hr.employees emp
)
where rn = 3
Whether to use rank()
, dense_rank()
or row_number()
depends on how you want to handle ties.
If you use row_number()
you will get the third row in the table sorted by salary descending. Would this be correct if you have two employees earning the highest salary? Or indeed four such lucky employees)?
If you use rank()
the subquery will return gaps in the ranking if there are ties, e.g. 1st, 2nd=, 2nd=, 4th, so you won't get any result for third place.
On the other hand dense_rank()
doesn't have gaps if there are ties, e.g. 1st, 2nd=, 2nd=, 3rd. That is why I used it above.
For the record, the equivalent query using rownum
would require an additional nested subquery.
select * from (
select emp.*
, rownum as rn
from
( select * from hr.employees
order by salary desc) emp
)
where rn = 3
This has the same outcome as the row_number()
analytic solution, that is it ignores ties.
回答2:
For your case, you need to determine rownum
in a subquery without order by clause :
select * from
(
select rownum as rn, ee.*
from (
select e.* from employees e order by salary desc
) ee
)
where rn=3;
P.S. Using analytic functions is better as APC told
来源:https://stackoverflow.com/questions/53757604/specific-row-number-with-all-the-fields