Friday 8 June 2012

How does one select the TOP N rows from a table or N th salary from emp table.

From Oracle 9i onwards, the RANK() and DENSE_RANK() functions can be used to determine the TOP N rows. Examples:

Get the top 10 employees based on their salary


SELECT ename, sal 
  FROM ( SELECT ename, sal, RANK() OVER (ORDER BY sal DESC) sal_rank
           FROM emp ) 
 WHERE sal_rank <= 10;


Select the employees making the top 10 salaries


SELECT ename, sal 
  FROM ( SELECT ename, sal, DENSE_RANK() OVER (ORDER BY sal DESC) sal_dense_rank
           FROM emp ) 
 WHERE sal_dense_rank <= 10;

For Oracle 8i and above, one can get the Top N rows using an inner-query with an ORDER BY clause:

From Oracle 9i onwards, the RANK() and DENSE_RANK() functions can be used to determine the TOP N rows. Examples:

Get the top 10 employees based on their salary



SELECT ename, sal 
  FROM ( SELECT ename, sal, RANK() OVER (ORDER BY sal DESC) sal_rank
           FROM emp ) 
 WHERE sal_rank <= 10;


Select the employees making the top 10 salaries



SELECT ename, sal 
  FROM ( SELECT ename, sal, DENSE_RANK() OVER (ORDER BY sal DESC) sal_dense_rank
           FROM emp ) 
 WHERE sal_dense_rank <= 10;

For Oracle 8i and above, one can get the Top N rows using an inner-query with an ORDER BY clause:
SELECT *
  FROM my_table a
 WHERE 10 >= (SELECT COUNT(DISTINCT maxcol)
                FROM my_table b
               WHERE b.maxcol >= a.maxcol)
 ORDER BY maxcol DESC;


To get top 10 earners of the company:
select * from(select * from emp order by sal desc) where rownum<11; OR
select * from(select * from emp order by sal desc) where rownum<=10;

or

SELECT empno, ename, job, mgr, hiredate, sal, comm, deptno
FROM (SELECT ROW_NUMBER () OVER (PARTITION BY deptno ORDER BY sal DESC) rn,
empno, ename, job, mgr, hiredate, sal, comm, deptno
FROM emp)
WHERE rn = n;

Where rn=1 lists all the top employees in Each Department.

For yours, where rn<=n will list the top 5 Employees in each Dept

OR

select ename
        ,sal
        ,dense_rank() over (order by sal desc) ranking
  from   emp;
or
select *
  from
  (
    select ename
          ,sal
          ,dense_rank() over (order by sal desc) ranking
    from   emp
  )
  where ranking = n -- Replace n with any value of as 1,2,3,4,.........
  /

No comments:

Post a Comment