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