【发布时间】: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
我有这张桌子:
ID action
1 buy
1 sell
1 drop
我想把它变成这个
ID buy sell drop
1 Yes Yes Yes
就是这样。
【问题讨论】:
标签: sql postgresql group-by pivot
使用条件聚合:
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
【讨论】: