我有一张这样的桌子:
雇员
EmpID | EmpName |EmpSalary | DEpartment
然后是另一张桌子
奖金
EmpID |EmpBonus
如何获得每个部门最高薪的员工,包括他们的奖金?
我有一张这样的桌子:
雇员
EmpID | EmpName |EmpSalary | DEpartment
然后是另一张桌子
奖金
EmpID |EmpBonus
如何获得每个部门最高薪的员工,包括他们的奖金?
如果您使用的是 SQL-Server,请使用ROW_NUMBER
或DENSE_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
在 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
尝试这个:
select EmpID (EmpSalary+EmpBonus) as total_salary
from Employees e LEFT JOIN Bonuses b
order by total_salary desc
limit 1
我不知道您使用的是哪个 SGBD,因此限制 1 可能是错误的。按照你的情况去做。