MS Access:如何从汇总月度数据的查询中创建YTD历史记录表?

时间:2015-01-18 12:59:19

标签: sql ms-access-2010

我有一张表,我每个月都会添加一个新月份的新数据记录(关键绩效指标)。该表由30个字段/列组成。出于这个问题的目的,我只包括三个字段。

Table: tbl_KPIMonth, Primary Key: YearMonth
YearMonth  OrderAmount   OrderLines  OrderLinesOnTime
201311     2500          350         330
201312     3000          400         390
201401     1000          100          95
201402      500          150         140
201403     2000          200         190
201404     1500          100          90

我有一个查询,将每月数据汇总到每个字段/列的当前年初至今(YTD)总数。

SELECT Val(Left(m.YearMonth,4)) AS Year, Sum(m.OrderAmount) AS OrderAmountYTD, 
Sum(m.OrderLines) AS OrderLinesYTD, 
Sum(m.OrderLinesOnTime)/Sum(m.OrderLines) AS OnTimeDeliveryYTD
FROM tbl_KPIMonth AS m
WHERE Val(Left(m.YearMonth,4))=2014
GROUP BY Val(Left(m.YearMonth,4))

每个月我都想将YTD汇总数据添加到历史记录表中以显示度量的进度。预期结果应如下所示:

Table: tbl_HistKPIYear,  Primary Key: YearMonth
YearMonth   OrderAmountYTD   OrderLinesYTD   OnTimeDeliveryYTD
201401      1000             100             0.95
201402      1500             250             0.94
201403      3500             450             0.94
201404      5000             550             0.93

如果我包含字段YearMonth,则使用上面的查询作为INSERT查询不起作用,因为GROUP BY m.YearMonth会阻止聚合其余字段。
我必须在YearMonth上设置主键以避免重复。

INSERT INTO tbl_HistKPIYear (OrderAmountYTD, OrderLinesYTD, OnTimeDeliveryYTD)

SELECT Sum(m.OrderAmount) AS OrderAmountYTD, 
Sum(m.OrderLines) AS OrderLinesYTD, 
Sum(m.OrderLinesOnTime)/Sum(m.OrderLines) AS OnTimeDeliveryYTD
FROM tbl_KPIMonth AS m
WHERE Val(Left(m.YearMonth,4))=2014
GROUP BY Val(Left(m.YearMonth,4))

如何在表tbl_HistKPIYear中填写当前月份(例如201404)的字段YearMonth?

1 个答案:

答案 0 :(得分:0)

您实际上需要一个累积查询,需要子查询才能在同一年内实现每个月的运行总和。

请参阅下面的示例(我添加OrderLineYTD以向您展示如何计算最后一列):

SELECT t1.YearMonth, 

(SELECT SUM(t2.OrderAmount) FROM tbl_KPIMonth t2 
WHERE t2.YearMonth <= t1.YearMonth AND Left(t1.YearMonth, 4) = Left(t2.YearMonth, 4)) As OrderAmountYTD,

(SELECT SUM(t2.OrderLines) FROM tbl_KPIMonth t2 
WHERE t2.YearMonth <= t1.YearMonth AND Left(t1.YearMonth, 4) = Left(t2.YearMonth, 4)) As OrderLinesYTD,

(SELECT SUM(t2.OrderLinesOnTime) FROM tbl_KPIMonth t2 
WHERE t2.YearMonth <= t1.YearMonth AND Left(t1.YearMonth, 4) = Left(t2.YearMonth, 4)) As OrderLineOnTimeYTD,

([OrderLineOnTimeYTD] / [OrderLinesYTD]) As OnTimeDeliveryYTD

FROM tbl_KPIMonth t1;

注意最后一列我引用了查询的新列别名,而不是再次重复子查询。