Skip to content
Advertisement

Updating a field to One-to-many relation field sum

I added a field to my existing table and now I have to update the old entries to have the right values.

UPDATE shift_job 
SET elapsed_time = ROUND(EXTRACT(EPOCH FROM actual_end_time - actual_start_time)/60):

ALTER TABLE shift_worker ADD COLUMN actual_work_duration integer NULL;
UPDATE shift_worker
SET actual_work_duration = SUM(SELECT elapsed_time
FROM shift_job 
WHERE shift_worker_id = shift_worker.id);

I calculated the elapsed_time for a job and that worked fine. When trying to calculate actual_work_duration for workers I ran into problems. I need to sum all “elapsed_time” fields where shift_worker.id = shift_job.shift_worker_id.

How can I achieve this?

Advertisement

Answer

UPDATE shift_worker
SET actual_work_duration = (SELECT SUM(elapsed_time)
FROM shift_job 
WHERE shift_worker_id = shift_worker.id);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement