0

我有一个看起来像这样的数据库:

Year    Month        New Visitor?
2011    Jan            Yes
2011    Jan            No
2012    Feb            No
2012    Feb            No
2012    Feb            Maybe

我希望每个月将 Yes 和 No 分开列,这样我就可以将其打印为图表。我知道要做到这一点,我需要这样的结果:

Year    Month         Yes       No     Maybe
2011    Jan            1         1       0
2012    Feb            0         2       1

我怎么可能只使用 MySQL 来解决这个问题?

4

2 回答 2

1

尝试:

SELECT `Year`, `Month`,
    COUNT(IF (`New Visitor?` = 'Yes', 1, NULL)) AS `Yes`,
    COUNT(IF (`New Visitor?` = 'No', 1, NULL)) AS `No`,
    COUNT(IF (`New Visitor?` = 'Maybe', 1, NULL)) AS `Maybe`
    FROM `table`
    GROUP BY `Year`, `Month`;
于 2012-09-24T18:13:20.577 回答
1

您可以使用以下内容(参见SQL Fiddle with demo):

select year, month,
  sum(case when newVisitor = 'yes' then 1 else 0 end) yes,
  sum(case when newVisitor = 'No' then 1 else 0 end) no,
  sum(case when newVisitor = 'Maybe' then 1 else 0 end) maybe
from yourtable
group by year, month
于 2012-09-24T18:20:08.560 回答