sql - Postgres 根据某些条件设置最终值
问题描述
我的 Postgres 表有一个名为 status 的列,其中包含完成、失败或正在运行。基于这些值,我想设置最终结果,如果全部完成,则最终结果 = 完成,如果一个失败,则结果 = 失败,如果一个正在运行且没有失败的条目,则结果正在运行。
code | status | parent_code
1 | complete | 3
2 | running | 3
3 | ---- |
在上表中,对于 code = 3,我想将状态设置为 running。
此外,如果有人可以告诉我如何设置相同的触发器,那么每当发生更改时,我都希望保持父级的值更新。
解决方案
我将使用使用过滤聚合的子查询来计算总数以及失败、运行和完成的行数,并将其用于 UPDATE 语句:
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 status = 'running') as running,
count(*) filter (where status = 'failed') as failed,
count(*) filter (where 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