Access Crosstab subtotal columns

余生长醉 提交于 2020-01-05 07:39:48

问题


I have a following question regarding crosstabs in Access: How do I create a subtotal columns?

What I want to see as a result of the query is this:

          Nov 2010     Dec 2010     2010 Total     Jan 2011    Feb 2011 
Row1             2            4             17            3           2
Row2             8            6             35            7           5

How do I create these subtotals for the year? (It's ok, if the year data will be in the end, after all months) The problem is that I need to do this without hardcoding each year, the query should work with any dataset

Thanks in advance!


回答1:


Say we have raw [SalesData]

SalesYear   SalesMonth  Region  SalesTotal
---------   ----------  ------  ----------
2010        11          East    45
2010        11          West    58
2010        12          East    55
2010        12          West    63
2011        1           East    51
2011        1           West    54
2011        2           East    55
2011        2           West    61

We can create a [SalesTotals] query to combine the monthly sales totals with the yearly totals...

SELECT SalesYear & "-" & Format(SalesMonth, "00") AS SalesPeriod, Region, SalesTotal FROM SalesData
UNION ALL
SELECT SalesYear & "-Total", Region, SUM(SalesTotal) FROM SalesData GROUP BY SalesYear, Region;

...which produces

SalesPeriod Region  SalesTotal
----------- ------  ----------
2010-11     East    45
2010-11     West    58
2010-12     East    55
2010-12     West    63
2011-01     East    51
2011-01     West    54
2011-02     East    55
2011-02     West    61
2010-Total  East    100
2010-Total  West    121
2011-Total  East    106
2011-Total  West    115

Then we can do our crosstab query on the [SalesTotals] query...

TRANSFORM Sum(SalesTotals.[SalesTotal]) AS SumOfSalesTotal
SELECT SalesTotals.[Region]
FROM SalesTotals
GROUP BY SalesTotals.[Region]
PIVOT SalesTotals.[SalesPeriod];

...which produces

Region  2010-11 2010-12 2010-Total  2011-01  2011-02  2011-Total
------  ------- ------- ----------  -------  -------  ----------
East    45      55      100         51       55       106
West    58      63      121         54       61       115


来源:https://stackoverflow.com/questions/16202008/access-crosstab-subtotal-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!