1

不确定它是否可能,但我使用的是 Access 2010 并有下表

> Reference|| Start Date || Month 1 || Month 2 || Month 3 || month N 
> 123      || 01/02/2012 || 50      || 50      || 70      || 50 321     
> 321      || 12/05/2012 || 60      || 40      || 90      || 0

我想要实现的是将其转换为表格

Reference || Start date || January 12 || February 12 || March 12 || April 12 || May 12 ||..
123       || 01/02/2012 || 0          || 50          || 50       || 70       || 50     ||
321       || 12/05/2012 || 0          || 0           || 0        || 0        || 60     ||

考虑到第 1 个月与 1 月 12 日没有关系,这是否可能使用 Access,尽管它可以从 Start DAate 派生

问候莫迪斯

4

1 回答 1

1

从 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
于 2013-05-23T10:28:38.930 回答