Tuesday 5 March 2013

How to findout Nth Highest salary


Select sal from emp a
Where &n = (select count(*) from emp b
                       Where a.sal <= b.sal);

To find the 3rd highest salary of emp table:
Select a.sal from emp a
Where 3 = (select count(*) from emp b
                       Where a.sal <= b.sal);

Without Duplicate:
Select distinct(a.sal) from emp a
Where 3 = (select count(distinct(b.sal)) from emp b
                       Where a.sal <= b.sal);

To find the first 3 highest salaries (show all 3 salaries):
Select sal from emp a
  Where 2 >=  (select count(*) from emp b
  Where a.sal < b.sal);

Without Duplicate:
Select distinct (a.sal) from emp a
Where 2 >= (select count(distinct b.sal) from emp b
Where a.sal <= b.sal);

No comments:

Post a Comment