使用GROUP BY和条件语句创建表的摘要

时间:2015-03-16 11:10:18

标签: sql ms-access

我的表格如下所示:

Category    Year    Step1    Step2   Step3
ABC         2014    Yes      Yes     Yes
ABC         2014    No       No      Yes    
XYZ         2013    Yes      No      Yes 
XYZ         2014    No       Yes     No

我需要提取属于2014年的数据,并在每个步骤中打印不同的打印数量“是”。类似的东西:

Category Year  Step1 Step2 Step3
ABC      2014  1     1     2
XYZ      2014  0     1     0

到目前为止,我只能按年份对数据进行分组并检索行数。我是新的SQL,很难在互联网上找到特定于我所拥有的架构的解决方案。

感谢您的期待。

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合来完成此操作。这是MySQL(和标准SQL表单):

select category, year,
       sum(case when step1 = 'Yes' then 1 else 0 end) as Step1,
       sum(case when step2 = 'Yes' then 1 else 0 end) as Step2,
       sum(case when step3 = 'Yes' then 1 else 0 end) as Step3
from mytable
where year = 2014
group by category, year;

MS Access不支持case,因此您需要使用iif()