【问题标题】:Postgres perform aggregation on array or string_aggPostgres 对数组或 string_agg 执行聚合
【发布时间】:2020-03-05 13:09:40
【问题描述】:

我有一列是一串逗号分隔的元素,例如statuses= 'Initial,Initial,Completed,InProgress。我该怎么做这样的状态栏:

CASE
    WHEN <all statuses are 'Initial'> THEN 'Initial'
    WHEN <all statuses are 'Completed'> THEN 'Completed'
    ELSE 'InProgress'
END AS status

我试过bool_and(string_to_array(statuses,',')='Initial'),它不能编译。有什么建议吗?

【问题讨论】:

    标签: sql string postgresql csv case


    【解决方案1】:

    您可以使用 string_to_array()ALL 运算符来做到这一点:

    case 
        when 'Initial'   = ALL(string_to_array(statuses, ',')) then 'Initial'
        when 'Completed' = ALL(string_to_array(statuses, ',')) then 'Completed'
        else 'InProgress'
    end status
    

    Demo on DB Fiddle

    with t as (
        select 'Initial,Initial' statuses
        union all select 'Completed,Completed'
        union all select 'Initial,Completed,Other'
    )
    select 
        statuses,
        case 
            when 'Initial'   = ALL(string_to_array(statuses, ',')) then 'Initial'
            when 'Completed' = ALL(string_to_array(statuses, ',')) then 'Completed'
            else 'InProgress'
        end status
    from t
    
    状态 |地位 :------------------------ | :--------- 初始,初始 |最初的 已完成,已完成 |完全的 初始,完成,其他 |进行中

    【讨论】:

      猜你喜欢
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多