MYSQL将单个列中的两个不同值拆分为两列

时间:2018-10-10 02:36:37

标签: mysql sql

Database Table

我试图做一个查询,根据ID将'Y'和'N'的两个值分成两个不同的列,并计算每个ID出现的总次数。

SELECT exerciseId, count(frustrated) Frustrated from selfreportfrustration where frustrated = 'Y' group by exerciseId;

SELECT exerciseId, count(frustrated) NotFrustrated from selfreportfrustration where frustrated = 'N' group by exerciseId;

到目前为止,我只设法对每个值进行一个查询,但是我希望能够将其缩短为一个查询,以使程序正常工作。

3 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

select exerciseId, sum(frustrated = 'Y') as Frustrated,
       sum(frustrated = 'N') as NotFrustrated
from selfreportfrustration
group by exerciseId;

答案 1 :(得分:0)

我们将“ Y”或“ N”放在另一列:

SELECT frustrated, exerciseId,
  count(frustrated) Frustrated
from selfreportfrustration
group by frustrated, exerciseId;

答案 2 :(得分:0)

您可以将Count()聚合与If()条件函数一起使用。

尝试:

SELECT exerciseId, 
       COUNT( IF(frustrated = 'Y', exerciseId, NULL) ) AS frustrated, 
       COUNT( IF(frustrated = 'N', exerciseId, NULL) ) AS not_frustrated 
FROM selfreportfrustration 
GROUP BY exerciseId