我正在使用SQL Server并拥有以下3个表:
Employees
包含Name
,Sales
,Bonus1
,Bonus2
Departments
包含Name
,Score
DepartmentsMembers
包含Name
(Employees.Name
)列,部门(Departments.Name
)如何根据属于该属性的员工的Score
+ Sales
+ Bonus1
的总和来计算和更新每个部门的Bonus2
列的值部?
编辑:
根据Ali Adlavaran的回答,我得到了这个查询,以便返回每个部门的结果列表及其计算的Score
。
SELECT
DepartmentsMembers.Name, SUM(Sales + Bonus1 + Bonus2)
FROM
DepartmentsMembers Department
INNER JOIN
DepartmentsMembers ON Departments.Name = DepartmentsMembers.Name
INNER JOIN
Employees ON DepartmentsMembers.Name = Employees.Name
WHERE
DepartmentsMembers.Name = Departments.Name
GROUP BY
DepartmentsMembers.Name
如何在每个部门的更新声明中加入所有内容?
谢谢。
答案 0 :(得分:0)
应该是这样的:
UPDATE Departments
SET Score =
(
SELECT SUM(Sales + Bonus1 + Bonus2)
FROM DepartmentsMembers
INNER JOIN Employees ON Employees.Name = DepartmentsMembers.Name
WHERE DepartmentsMembers.Department = Departments.Name
GROUP BY DepartmentsMembers.Department
)
我希望对你有所帮助:)。
答案 1 :(得分:0)
首先,由部门总结:
SELECT dm.Department,
SUM(COALESCE(e.Sales, 0) + COALESCE(e.Bonus1, 0) + COALESCE(e.Bonus2, 0)) as total
FROM DepartmentsMembers dm INNER JOIN
Employees e
ON dm.EmployeeName = e.Name
GROUP BY dm.Department;
然后,您可以在部门更新中使用它:
UPDATE d
SET Score = de.total
FROM Departments d JOIN
(SELECT dm.Department,
SUM(COALESCE(e.Sales, 0) + COALESCE(e.Bonus1, 0) + COALESCE(e.Bonus2, 0)) as total
FROM DepartmentsMembers dm INNER JOIN
Employees e
ON dm.EmployeeName = e.Name
GROUP BY dm.Department
) de
ON de.Department = d.Name;
编辑:
如果您想确保所有部门都得到更新,请使用LEFT JOIN
:
UPDATE d
SET Score = COALESCE(de.total, 0) -- only needed if you don't want `NULL`s
FROM Departments d LEFT JOIN
(SELECT dm.Department,
SUM(COALESCE(e.Sales, 0) + COALESCE(e.Bonus1, 0) + COALESCE(e.Bonus2, 0)) as total
FROM DepartmentsMembers dm INNER JOIN
Employees e
ON dm.EmployeeName = e.Name
GROUP BY dm.Department
) de
ON de.Department = d.Name;