简体   繁体   中英

Update record in sql table with a sum of values from other table

Im new to SQL. I have a table employee , it has fields eID and eLoad . In addition i have table ongoing_projects it has pID , eID (those two are primary) and eLoad . Im trying to insert a sum of all eLoad s for each employee. I have an idea for pseudocode, but I cannot implement it. Any Ideas? Thank you!

For each eID in table employee
DO
UPDATE `employee` SET eload=(
  SELECT SUM (eload) as eload
  FROM ongoing_projects 
);

If I understood It, you would like to do something like:

UPDATE employee e
SET e.eLoad = (SELECT SUM(op.eLoad) FROM ongoing_projects op WHERE op.eID=e.eID);

It updates each row in employees.eLoad column with the sum of the ongoing_projects.eLoad where the ongoing_projects.eID=actual employee eID

Or if you would like to SUM employees.eLoad with the ongoing_projects eLoad then the query may look:

UPDATE employee e
SET e.eLoad = e.eLoad + (SELECT SUM(op.eLoad) FROM ongoing_projects op WHERE op.eID=e.eID);

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