简体   繁体   中英

update 2nd table column based on 1st table

I have two tables. One is Employee and other is Department .

Employee table has following columns:

Name | Salary | Department Id

Department table has

Department Id| Department Name | SumofSalary

I want to update SumofSalary department wise

Code I have tried

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
)

Following will give you sum of salaries department wise and update in department table.

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] 

You can try the below code a simple subquery Which will update the sum salary department wise

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM