2017-05-18 50 views
-1

我怎樣才能找到每個部門中最高工資的差額?前兩名員工每個部門的工資差額

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 
+4

,您正在使用哪個數據庫..? – Mansoor

+0

@Mansoor我正在使用MySql –

+0

向我們展示您嘗試過的內容,並解釋如果給定部門中兩個最高薪酬相同會發生什麼情況 – Strawberry

回答

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 
+0

得到輸出,但是我們可以減少複雜度,這裏我們得到NNN我們可以得到N * N –

+1

不要混淆任何命令式語言的基於集合的語言,如SQL ,他們沒有相同的運行時間。您可以通過添加索引來降低複雜性。 – Donnie

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 

使用與內部查詢加入到主表和導出與每個部門的最大差異如下所示。所以,最終的查詢:

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 
+0

獲得了輸出結果,但是我們是否可以降低複雜性,這裏是N * N * N可以得到N * N –

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 
相關問題