Thursday, 19 July 2012

Find Second and Third Height Salary in SQL Server

 --Find second height salary--

select MAX(salary) from emp2 where salary<(select MAX (salary ) from emp2)
--or
select max(salary) from emp where salary  not in (select distinct top 1  salary from emp order by salary desc )
--or
select min(salary) from emp where salary  in (select distinct top 2  salary from emp order by salary desc )

--find third height salary--
select max(salary) from emp where salary  not in (select distinct top 2  salary from emp order by salary desc )
--or
select min(salary) from emp where salary  in (select distinct top 3  salary from emp order by salary desc )

--find all details of emp where emp  salary have been second height--

select *from emp where salary in(select MAX(salary) from emp where salary not in(select distinct top 1 salary from emp order by salary desc))
--or
select *from emp where salary in(select MIN(salary) from emp where salary  in(select distinct top 2 salary from emp order by salary desc))

--Find all details of emp where emp salary is third height--

select *from emp where salary in(select MAX(salary) from emp where salary not in(select distinct top 2 salary from emp order by salary desc))
--or
select *from emp where salary in(select MIN(salary) from emp where salary  in(select distinct top 3 salary from emp order by salary desc))

No comments:

Post a Comment