简体   繁体   中英

How to find top 5 distinct salary in oracle using rownum keyword

select * from (select * from employees where salary in (select distinct salary from employees ) order by salary desc ) where rownum <=5

I'm unable to get distinct from the above query

You can use the DENSE_RANK analytical function as follows:

SELECT * FROM
    ( SELECT E.*,
             DENSE_RANK() OVER (ORDER BY SALARY DESC NULLS LAST) AS DRN
        FROM EMPLOYEES )
WHERE DRN <= 5;

You need to get employees records after get distinct salary in subquery:

select * from employees where salary in (select * from (select distinct salary from employees order by salary desc ) where rownum <=5)

Or use fetch first clause

select * from employees where salary in (select distinct salary from employees order by salary desc FETCH FIRST 5 ROWS ONLY) 

The fetch first clause, which can be combined with the result offset clause if desired, limits the number of rows returned in the result set. The fetch first clause can sometimes be useful for retrieving only a few rows from an otherwise large result set, usually in combination with an ORDER BY clause. The use of this clause can give efficiency benefits. In addition, it can make programming the application simpler.

You should use something like below.

First get the top 5 salaries and then get the employees having that salary

 select * from employees e inner join 
  (select * from (select distinct e.salary  from employees e order by e.salary desc ) 
  where rownum <=5 )e1 on e1.salary=e.salary

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM