我有这张桌子(StrategiesUsed):
receiverID strategies counts print
--------------------------------------------------------------
14 RationalPositive 12 0
14 EmotionalNegative 4 0
45 EmotionalPositive 17 1
154 RationalPositive 5 1
154 EmotionalPositive 6 1
154 EmotionalNegative 3 1
当我发出以下语句以将“策略”值作为列时:
select `receiverID`,
case when strategies like "EmotionalNegative" then `counts` end as EN,
case when strategies like "RationalPositive" then `counts` end as EP
from StrategiesUsed
group by receiverID
我明白了:
receiverID EN EP
14 NULL 12
45 NULL NULL
154 NULL 5
为什么NULL
列中只有EN
?我正在做与EP
完全相同的事情,根据表格,receiverID
14的“EmotionalNegative”为4,154为3。
如果我除了receiverID之外还按策略进行分组,我会得到
receiverID EN EP
14 4 NULL
14 NULL 12
45 NULL NULL
154 3 NULL
154 NULL NULL
154 NULL 5
但我真正想要的是:
receiverID EN EP
14 4 12
45 NULL NULL
154 3 5
有什么想法吗?我错过了什么?
答案 0 :(得分:2)
在第二次阅读问题后,我才意识到你错过了案例陈述的ELSE
部分:
case when strategies like "EmotionalNegative" then `counts` else 0 end
如果您当然可以有多个策略,请添加SUM
。
答案 1 :(得分:0)
如果对于每个receiverID,您的策略都是唯一的,那么应该这样做:
select
`receiverID`,
SUM(IF(strategies="EmotionalNegative", counts, 0)) as EN,
SUM(IF(strategies="RationalPositive", counts, 0)) as EP
from StrategiesUsed
group by receiverID