SQL - Find top two salary for each department

1. top 2 salary in each dept
2. 2nd maximum sal in each dept
3. 2nd minimum sal in each dept.

Questions by kalyan.sam

Showing Answers 1 - 22 of 22 Answers

1.top 2 salary in each dept
ans: select top 2 * from (select * from emp orderby sal desc)
                                      group by desc;
                                                

 2.2nd maximum sal in each dept

Select * From EMP A Where
(2-1) = (Select Count(Distinct(B.sal)) From EMP B Where B.sal >A.sal)


3. 2nd minimum sal in each dept.

Select * From EMP A Where
(2-1) = (Select Count(Distinct(B.sal)) From EMP B Where B.sal <A.sal)

mkaleelmd

  • Apr 7th, 2011
 

Top 2 salary for each department
-------------------------------------------------
SELECT * FROM

            (SELECT
                  employee_id,department_id,salary
                 ,dense_rank() OVER ( partition by department_id ORDER BY salary desc) as ranking
             FROM employees) a
WHERE a.ranking <=2

smonroy

  • Sep 23rd, 2011
 

Ok, you have two easy options to each problem, you choose the one that suits you

Maximium salary

Code
  1. 1 OPTION

  2.  

  3. Declare @A  int, @B  Int

  4. SET @A=(SELECT Max(sal) FROM Salary)

  5. SET @B=(SELECT Max(sal) FROM Salary WHERE sal<>@A)

  6. SELECT @A, @B

  7.  

  8. 2 OPTION

  9.  

  10. SELECT a=(SELECT max(sal) FROM Salary),

  11. b=(SELECT max(sal) FROM Salary

  12. WHERE sal <>(SELECT max(sal) FROM Salary))




Minimum salary

Code
  1. 1 OPTION

  2. Declare @A  int, @B  Int

  3. Set @A=(Select min(sal) from Salary)

  4. Set @B=(Select min(sal) from Salary where sal<>@A)

  5. Select @A, @B

  6.  

  7. 2 OPTION

  8. select a=(select min(sal) from Salary),

  9. b=(select min(sal) from Salary

  10. where sal<>(select min(sal) from Salary))

  11.  

  12.  


ashadevi21

  • Sep 27th, 2011
 

The Same can be modified and can be used for 2nd maximum and 2nd minimum as well

For 2nd Maximum
===========
SELECT dept_id, salary FROM
(SELECT
dept_id, salary
,DENSE_RANK() OVER ( PARTITION BY dept_id ORDER BY salary DESC) AS ranking
FROM EMPLOYEE ) a
WHERE a.ranking =2

For 2nd Minimum
==========
SELECT dept_id, salary FROM
(SELECT
dept_id, salary
,DENSE_RANK() OVER ( PARTITION BY dept_id ORDER BY salary ) AS ranking
FROM EMPLOYEE ) a
WHERE a.ranking =2

  Was this answer useful?  Yes

Prasanth

  • Sep 12th, 2022
 

SELECT d.department_id, d.salary, d.employee_id FROM
(SELECT employee_id, department_id, salary, dense_rank() over(partition by department_id order by salary desc ) as salary_DenseRank from employees) d
WHERE d.salary_DenseRank =2;

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions