Postgres 查询根据状态条件将多行合并为一个

Postgres Query to Combine multiple Rows into one based on Status Condition

我有以下数据的示例

Col1 Col2 Status
a    ab   Failed
a    bc   Running
a    cd   Completed

我期望的输出是

Col1 Status
a    Failed

即任何一个 Subjob(Col2) 失败,那么 Main job 应该显示为 Failed

一个选项使用 distinct on 和条件排序:

select distinct on (col1) col1, status
from mytable
order by 
    col1,
    case status
       when 'Failed'    then 0
       when 'Running'   then 1
       when 'Completed' then 2
    end

这会优先考虑“失败”状态,其次是“运行”,然后是“已完成”。

您也可以使用布尔值进行排序,例如:

order by 
    col1,
    (status = 'Failed')    desc,
    (status = 'Running')   desc,
    (status = 'Completed') desc

我认为对您提出的问题最简单的回答是:

select distinct col1, status
from t
where status = 'Failed';

这将 return 所有失败的 col1

如果您有其他问题,则应将其作为 问题提出。清楚地解释您的逻辑,并提供涵盖您需要沟通的主要场景的样本数据和预期结果。