我有一个类似这样的数据库:
Year Month New Visitor?
2011 Jan Yes
2011 Jan No
2012 Feb No
2012 Feb No
2012 Feb Maybe
我希望Yes's和No's是每月独立的专栏,所以我可以将它打印成图表。我明白要做到这一点,我需要这样的结果:
Year Month Yes No Maybe
2011 Jan 1 1 0
2012 Feb 0 2 1
我怎样才能使用MySQL?
答案 0 :(得分: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`;
答案 1 :(得分: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