如何根据以下内容选择部门中收入最高的员工?

时间:2013-09-17 09:00:59

标签: sql

我有一张这样的表:

员工

EmpID | EmpName |EmpSalary | DEpartment

然后是另一个表

奖金

EmpID |EmpBonus

如何才能获得每个部门薪酬最高的员工,包括他们的奖金?

3 个答案:

答案 0 :(得分:4)

如果您使用的是SQL-Server,请使用ROW_NUMBERDENSE_RANK(如果您想要包含关联):

WITH CTE AS(
    SELECT e.EmpID,e.EmpName,e.EmpSalary, e.Department,b.EmpBonus,
       RN = ROW_NUMBER() OVER (PARTITION BY Department 
                               ORDER BY (EmpSalary + COALESCE(EmpBonus,0)) DESC)
    FROM Employees e LEFT OUTER JOIN Bonuses b
       ON e.EmpID = b.EmpID 
)
SELECT EmpID, EmpName, EmpSalary, Department, EmpBonus
FROM CTE
WHERE RN = 1

Ranking Functions

答案 1 :(得分:-1)

在SQL Server中

SELECT top 1 e.EmpID,e.EmpName,e.Department,
sum(EmpSalary + EmpBonus) as total_salary
FROM Employees e INNER JOIN Bonuses b
ON e.EmpID = b.EmpID 
group by e.EmpID,e.EmpName,e.Department
order by total_salary desc

在MySQL中

SELECT e.EmpID,e.EmpName,e.Department,
sum(EmpSalary + EmpBonus) as total_salary
FROM Employees e INNER JOIN Bonuses b
ON e.EmpID = b.EmpID 
group by e.EmpID,e.EmpName,e.Department
order by total_salary desc limit 1

答案 2 :(得分:-1)

试试这个:

select EmpID (EmpSalary+EmpBonus) as total_salary
from Employees e LEFT JOIN Bonuses b
order by total_salary desc
limit 1

我不知道您使用的是哪个SGBD,因此限制1可能是错误的。这样做是如何适用于你的情况。