每个部门最高2名员工的工资差异

时间:2017-05-18 04:50:26

标签: mysql sql database

如何找到各部门薪酬最高的薪酬差异。

DeptID      EmpName   Salary
Engg        Sam       10000
Engg        Smith     15000
HR          Denis     20000
HR          Archie    15000
HR          Danny     30000
IT          David     25000
IT          Chrish    40000
IT          John      35000

结果应为

DeptID   Salary
Engg       5000
HR         10000
IT         5000

3 个答案:

答案 0 :(得分:1)

您可以使用子查询

SELECT
  DeptID,
  (MAX(Salary) - (SELECT
    MAX(Salary)
  FROM your_table
  WHERE DeptID = yt.DeptID
  AND Salary <
  MAX(yt.Salary))
  ) sal_diff
FROM your_table yt
GROUP BY DeptID
ORDER BY DeptID

答案 1 :(得分:0)

从以下查询中找出每个deptId的第二个最高工资

-- Assuming a temp table named as #salary

select deptid, max(salary) as MaxSal_2nd from #salary 
where salary not in (select max(salary) from #salary group by deptid)
group by deptid

将该查询与内部联接一起使用到主表,并使用max sal per deptId导出差异,如下所示。所以,最终查询:

select s.deptid,max(salary)-Max(dt.MaxSal_2nd) from #salary s
inner join
(select deptid, max(salary) as MaxSal_2nd from #salary 
where salary not in (select max(salary) from #salary group by deptid)
group by deptid)dt  --Second Max Salary per deptId
on s.deptid=dt.deptid
group by s.deptid

答案 2 :(得分:0)

使用窗口functoins获取部门内的薪资等级,然后转动并寻找前2名工资并找出差异。

select 
baseq.DeptID,
max(case when baseq.SalaryRank=1 then baseq.Salary else 0 end) - max        
(case     when baseq.SalaryRank=2 then baseq.Salary else 0 end)
from
(
    select DeptID, EmpName, Salary, Rank() over (parition by DeptID order by 
    Salary Desc) as SalaryRank
    from TestTable
) baseq
group by baseq.DeptID