Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 分组并替换_Sql_Postgresql_Group By_Aggregate Functions - Fatal编程技术网

Sql 分组并替换

Sql 分组并替换,sql,postgresql,group-by,aggregate-functions,Sql,Postgresql,Group By,Aggregate Functions,我有一张这样的桌子: groupe subgroup id status A a 1 up A b 1 notdefined A c 1 null A a 2 up A b 2 up A c 2 up A a 3 up A

我有一张这样的桌子:

groupe  subgroup    id  status
A          a       1    up
A          b       1    notdefined
A          c       1    null
A          a       2    up
A          b       2    up
A          c       2    up
A          a       3    up
A          b       3    up
A          c       3    null
我需要的是为每个组合(组id)返回一个指定的状态 如果每个(组、id)的状态为notdefined,则返回notdefined的全局状态

如果所有状态=向上返回全局状态=向上 如果有up,但没有指定null返回

所以结果应该是这样的

Groupe      id      global_status
A            1       notdefined
A            2        up
A            3        notspecified

我在

上尝试了一些东西。您可以使用聚合和条件逻辑:

select groupe, id,
       (case when count(*) filter (where status = 'notdefined') > 0
             then 'notdefined'
             when count(*) filter (where status is null) > 0
             then 'notspecified'
             when max(status) = min(status) and min(status) = 'up'
             then 'up'
             else 'something else'
        end) as global_status
from t
group by groupe, id;
使用

select 
   groupe, 
   id, 
   case 
      when bool_and(status = 'up') then 'up' 
      when bool_or(status = 'notdefined') then 'notdefined' 
      else 'notpecified' 
   end as status
from tab
group by 1, 2
order by 1, 2