Postgres 聚合案例

Postgres aggregate with case

我有一些查询 returns a table "code_1"(id - distinct).

|---------------------|------------------|
|         id          |       status     |
|---------------------|------------------|
|          1          |         true     |
|---------------------|------------------|
|          2          |         true     |
|---------------------|------------------|
|          3          |         false    |
|---------------------|------------------|
|          3          |         true     |
|---------------------|------------------|
|          4          |         false    |
|---------------------|------------------|

根据数据..我想得到以下 table ("code_2")

|---------------------|------------------|
|     id              |     status       |
|---------------------|------------------|
|          1          |      include     |
|---------------------|------------------|
|          2          |      include     |
|---------------------|------------------|
|          3          |      partial     |
|---------------------|------------------|
|          4          |      exclude     |
|---------------------|------------------|

如果 id 重复 status 是部分的,否则 status = status from code_1 table

如果我没理解错,请使用聚合:

select id,
       (case when min(status) = max(status) and min(status) then 'Include'
             when min(status) = max(status) and not min(status) then 'Exclude'
             else 'Partial'
        end) as status
from t
group by id;

或者,使用布尔聚合函数:

select id,
       (case when bool_and(status) then 'Include'
             when bool_or(status) then 'Partial'
             else 'Exclude'
        end) as status
from t
group by id;