透视具有多列和计数

时间:2017-01-05 11:32:43

标签: sql ms-access pivot transform

相当新的SQL并且此刻完全丢失了。我的桌子看起来像这样:

 AccountNr  |     Year1     |    Year2
-----------------------------------------
       121  |      New     |      N/A
       131  |   Recurring  |      New
       116  |   Recurring  |     Recurring
       123  |    Inactive  |     Recurring
       112  |   Invactive  |     Inactive

如此简单地显示客户在特定年份的帐户状态。我需要的是计算我在Year1,Year2和以下所有期间有多少新的,非活动的,重复的和N / A帐户。理想情况下,我希望它看起来像这样:

Status      |   Year1      |   Year2 
-----------------------------------------
      New   |      1       |      1
 Recurring  |      2       |      2
 Inactive   |      2       |      1
   N/A      |      0       |      1

不必看起来像这样,它只需计算每年每个状态的帐户数量。我顺便使用MS Access。

感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

我不认为您可以使用单个查询在MS Access中一致地执行此操作。对于您的特定数据,您可以执行以下操作:

select y2.status, nz(y2.year1, 0) as year1, y2.year2
from (select t.year2 as status, count(*) as year2
      from t
      group by t.year2
     ) as y2 left outer join
     (select t.year1 as status, count(*) as year1
      from t
      group by t.year1
     ) as y1
     on y1.status = y2.status;

这是有效的,因为所有状态都在year2列中。

如果你有一个单独的状态表,你可以这样做:

select s.status, nz(y2.year1, 0) as year1, nz(y2.year2, 0) as year2
from statuses as s left outer join
     (select year2 as status, count(*) as year2
      from t
      group by year2
     ) as y2
     on y2.status = s.status left outer join
     (select year1 as status, count(*) as year1
      from t
      group by year1
     ) as y1
     on s.status = y1.status;