我有两张桌子。一个是Employee
,另一个是Department
。
Employee表包含以下列:
Name | Salary | Department Id
部门表有
Department Id| Department Name | SumofSalary
我想明智地更新SumofSalary部门
我试过的代码
update Department set sumofsalary =
(
select D.deptid, SUM(E.salary) from Department D inner join Employesalary E
on d.deptid=e.deptid group by D.deptid
)
以下将为您提供工资部门的总和,并在部门表中更新。
UPDATE D SET D.SumOfSalary = T.Salary FROM Department D JOIN
(
SELECT SUM(Salary) Salary, [Department ID] DeptID FROM Employee Group By [Deptartment ID]
) T ON T.DeptID = D.[Department ID]
您可以尝试下面的代码一个简单的子查询,它将明智地更新总薪资部门
UPDATE dept
SET dept.sum =h.totalSum FROM (select a.deptid, SUM( a.Salary) AS
totalSum FROM emp a
Group By a.deptid) h WHERE
dept.deptid=h.deptid