1

我有这张表(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

为什么列中只有NULLs EN?我正在做与我所做的完全相同的事情EP,根据表格,“EmotionalNegative”中有 4表示 14,3receiverID表示 154。

如果除了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

有任何想法吗?我错过了什么?

4

2 回答 2

2

在第二次阅读这个问题后,我刚刚意识到你错过ELSE了案例陈述的一部分:

case when strategies like "EmotionalNegative" then `counts` else 0 end

当然,如果您可以有多个策略,请添加SUM.

于 2013-09-17T03:06:08.643 回答
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
于 2013-09-17T03:10:47.290 回答