如何将多个变量列转换为许多不同的布尔列?

时间:2020-09-16 10:11:27

标签: sql postgresql group-by pivot

我有这张桌子:

ID     action
1       buy
1       sell
1       drop

我想把它变成这个

 ID     buy     sell     drop
 1      Yes     Yes       Yes

仅此而已。

1 个答案:

答案 0 :(得分:3)

使用条件聚合:

select
    id,
    bool_or(action = 'buy')  has_buy,
    bool_or(action = 'sell') has_sell,
    bool_or(action = 'drop') has_drop
from mytable
group by id

这将在新列中为您提供布尔值(真或假),而不是是/否字符串,这就是您在问题中所描述的。

如果您想要是/否,则:

select
    id,
    case when bool_or(action = 'buy')  then 'Yes' else 'No' end has_buy,
    case when bool_or(action = 'sell') then 'Yes' else 'No' end has_sell,
    case when bool_or(action = 'drop') then 'Yes' else 'No' end has_drop
from mytable
group by id
相关问题