Both the above answer given by @a_horse_with_no_name and @Gordon Linoff is correct.
Here I have converted it to stored procedure and written a trigger for the same.
It might be helpful for someone.
- Writing a Stored Procedure.
- Creating a trigger.
Writing a Stored Procedure.
CREATE OR REPLACE FUNCTION UpdateStatus()
RETURNS TRIGGER AS $$
BEGIN
update the_table tt
set status = case
when x.failed > 0 then 'failed'
when x.running > 0 then 'running'
when x.total_rows = x.completed then 'completed'
end
from (
select parent_code,
count(*) as total_rows,
count(*) filter (where device_discovery_status = 'running') as running,
count(*) filter (where device_discovery_status = 'failed') as failed,
count(*) filter (where device_discovery_status = 'completed') as completed
from the_table
where parent_code is not null
group by parent_code
) x
where tt.parent_code is null
and tt.code = x.parent_code;
RETURN NULL;
END;
$$
LANGUAGE plpgsql;
Creating a trigger.
CREATE TRIGGER update_status_on_change
AFTER UPDATE ON the_table
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE PROCEDURE UpdateStatus();
So whenever a status gets changed update_status_on_change trigger will be triggered and it will set the final status accordingly.
parent_codecorrespond?code