从 UNION 查询开始以“取消透视”您的数据:
SELECT Reference, [Start Date], 0 AS [Month Offset], [Month 1] AS Qty
FROM TableN
UNION ALL
SELECT Reference, [Start Date], 1 AS [Month Offset], [Month 2] AS Qty
FROM TableN
UNION ALL
SELECT Reference, [Start Date], 2 AS [Month Offset], [Month 3] AS Qty
FROM TableN
UNION ALL
SELECT Reference, [Start Date], 3 AS [Month Offset], [Month 4] AS Qty
FROM TableN
重复 UNION ALL 模式,直到在原始表中包含所有 [Month N] 字段。将此查询另存为 [QtyByMonth]。结果应该是这样的
Reference Start Date Month Offset Qty
--------- ---------- ------------ ---
123 2012-02-01 0 50
321 2012-05-12 0 60
123 2012-02-01 1 50
321 2012-05-12 1 40
123 2012-02-01 2 70
321 2012-05-12 2 90
123 2012-02-01 3 50
321 2012-05-12 3 0
现在创建一个查询,该查询创建您将按月执行交叉表的基础:
SELECT
Reference,
[Start Date],
DateAdd("m", [Month Offset], DateSerial(Year([Start Date]), Month([Start Date]), 1)) AS [FirstOfMonth],
Qty
FROM QtyByMonth
……归来……
Reference Start Date FirstOfMonth Qty
--------- ---------- ------------ ---
123 2012-02-01 2012-02-01 50
321 2012-05-12 2012-05-01 60
123 2012-02-01 2012-03-01 50
321 2012-05-12 2012-06-01 40
123 2012-02-01 2012-04-01 70
321 2012-05-12 2012-07-01 90
123 2012-02-01 2012-05-01 50
321 2012-05-12 2012-08-01 0
将该查询另存为 [BasisForXtab]。现在基于此构建您的交叉表...
TRANSFORM Sum(BasisForXtab.Qty) AS SumOfQty
SELECT BasisForXtab.Reference, BasisForXtab.[Start Date]
FROM BasisForXtab
GROUP BY BasisForXtab.Reference, BasisForXtab.[Start Date]
PIVOT Format([FirstOfMonth],"yyyy-MM");
……归来……
Reference Start Date 2012-02 2012-03 2012-04 2012-05 2012-06 2012-07 2012-08
--------- ---------- ------- ------- ------- ------- ------- ------- -------
123 2012-02-01 50 50 70 50
321 2012-05-12 60 40 90 0