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

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

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

  1. Id | status
  2. ____________
  3. 23 | complete
  4. 24 | going on
  5. 34 | failed
  6. 56 | complete

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

  1. Result | tableName
  2. ___________________
  3. Failed | Table1

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

  1. Result | tableName
  2. ___________________
  3. Going on | Table1

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

  1. Result | tableName
  2. ___________________
  3. Complete | Table1

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

  1. 1. Failed
  2. 2. Going on
  3. 3. Complete

有人能帮我吗?

3xiyfsfu

3xiyfsfu1#

我认为您需要条件聚合:

  1. select
  2. case
  3. when count(*) filter(where status = 'failed') > 0 then 'failed'
  4. when count(*) filter(where status = 'going on') > 0 then 'going on'
  5. when count(*) > 0 then 'complete'
  6. end result
  7. from mytable

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

  1. select status
  2. from mytable
  3. order by
  4. status = 'failed' desc,
  5. status = 'going on' desc,
  6. status = 'complete' desc
  7. limit 1

db小提琴演示

展开查看全部

相关问题