如何根据postgres中其他列的值插入单行的文本列

ckocjqey  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(246)

我想根据特定参数的值插入sigal行的文本结果。
例如。
表1

Id | status
____________
23 | complete
24 | going on
34 | failed
56 | complete

现在在表1中,如果任何一个或多个条目的状态为“failed”,那么我的查询结果应该是:

Result | tableName
___________________
Failed | Table1

如果任何一个或多个条目的状态为“继续”,并且没有任何行的状态为“失败”,则我的查询结果应为:

Result | tableName
___________________
Going on | Table1

最后,如果“状态”列中的所有值均为“完成”,则结果应为:

Result | tableName
___________________
Complete | Table1

总之,查询结果基于“状态”列,优先级为:

1. Failed
2. Going on
3. Complete

有人能帮我吗?

3xiyfsfu

3xiyfsfu1#

我认为您需要条件聚合:

select
    case
        when count(*) filter(where status = 'failed')   > 0 then 'failed'
        when count(*) filter(where status = 'going on') > 0 then 'going on'
        when count(*)                                   > 0  then 'complete'
    end result
from mytable

您还可以使用条件排序和行限制子句来执行此操作,这可能更有效:

select status
from mytable
order by 
    status = 'failed'   desc,
    status = 'going on' desc,
    status = 'complete' desc
limit 1

db小提琴演示

相关问题