Quality Testing

Quality is delighting customers

How we find third, Fourth and Fifth highest salary through SQl queries?

How we find third, Fourth and Fifth highest salary through SQl queries?
Please write SQl Query.

Thanks

Views: 937

Reply to This

Replies to This Discussion

For third maximum salary,consider the emp table

      SELECT max(sal) from emp

      where sal < (select max(sal) from emp

      where sal < (select max(sal) from emp ) )

       In that way you write fourth and fifth max salary for the emp table...

 

 

Hi,

Thanks for reply.

for second highest salary we can write -

SELECT max(sal) from emp

      where sal < (select max(sal) from emp)

Please correct me.

is there any another way to write second, third, fourth and fifth maximum salary ?

Thanks

Hitesh Shah

 

hi hitesh we can use TOP and NOT IN

 

2nd Highest Salary

select max(salary) from Employeedetails
where salary not in (select top 1 salary from Employeedetails order by salary desc )

3nd Highest Salary

select max(salary) from Employeedetails
where salary not in (select top 2 salary from Employeedetails order by salary desc )

4nd Highest Salary

select max(salary) from Employeedetails
where salary not in (select top 3 salary from Employeedetails order by salary desc )

...................

 

Hi,

Really very easy query we can use.

Thanks for it.

Hitesh Shah

Hi prasad ,

                  How we find the nth maximum salary from the emp table ?

select max(salary) from Employeedetails

to get n max sal

select top 1 esal from emp order by esal desc

Finding nth highest salary:

select rownum, empno, ename, sal from (select * from emp order by sal desc) group by rownum, empno, ename, sal having rownum='&n';

Note : rownum is the inbuilt field / column, we can't see the rownum field / column in the table. By default it will take the values as 1, 2, 3, .........

we can write this way also,

select max(sal) from emp where sal< (select top2 sal from emp orderby sal desc)....

This will give the 3rd highest sal....

With out using top

select a.sal from emp a

where n=(select count(distinct(b.sal) from emp b) where a.sal<b.sal)

if we want 3rd highest n=4,to get "nth" max ,specify a number "n-1" in place of n

select rownum , slary from employee where rownum in (''3','4','5') order by salary desc

This will work for Oracle.

For SQL server rank function will be used

Hi,

SELECT LEVEL,MAX(SAL) FROM EMP  WHERE LEVEL IN (3,4,5)  CONNECT BY PRIOR SAL > SAL  GROUP BY LEVEL;

Thanks

RSS

TTWT Magazine

Advertisement

You Can


Call for Articles

Advertisement

Videos

  • Add Videos
  • View All

Badge

Loading…

© 2012   Created by Quality Testing.

Badges  |  Report an Issue  |  Terms of Service