【问题标题】:How to convert a multiple variables column into many different boolean columns?如何将多个变量列转换为许多不同的布尔列?
【发布时间】:2021-01-03 03:39:38
【问题描述】:

我有这张桌子:

ID     action
1       buy
1       sell
1       drop

我想把它变成这个

 ID     buy     sell     drop
 1      Yes     Yes       Yes

就是这样。

【问题讨论】:

    标签: sql postgresql group-by pivot


    【解决方案1】:

    使用条件聚合:

    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
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多