我在问题的编辑历史记录中找到了表名和字段名,因此在此答案中使用了这些名称。您没有提供record_matYields示例数据,因此我创建了自己的示例数据并希望它适用:
id reportDate gainOrLoss 1 12/28/2011 $1,500.00 2 12/29/2011 $500.00 3 12/30/2011 $1,000.00 4 1/2/2012 $10.00 5 1/3/2012 $4,500.00 6 1/4/2012 $900.00
首先,我创建了 qryMonthlyLosses 。这是SQL和输出:
SELECt Year(reportDate) AS reportYear, Month(reportDate) AS reportMonth, Min(y.reportDate) AS MinOfreportDate, Sum(y.gainOrLoss) AS SumOfgainOrLossFROM record_matYields AS yGROUP BY Year(reportDate), Month(reportDate);reportYear reportMonth MinOfreportDate SumOfgainOrLoss 2011 12 12/28/2011 $3,000.00 20121 1/2/2012 $5,410.00
我使用了第一个查询来创建另一个 qryCumulativeLossesByMonth :
SELECt q.reportYear, q.reportMonth, q.MinOfreportDate, q.SumOfgainOrLoss, ( SELECT Sum(z.gainOrLoss) FROM record_matYields AS z WHERe z.reportDate < q.MinOfreportDate ) AS PreviousGainOrLossFROM qryMonthlyLosses AS q;reportYear reportMonth MinOfreportDate SumOfgainOrLoss PreviousGainOrLoss 2011 12 12/28/2011 $3,000.00 20121 1/2/2012 $5,410.00 $3,000.00
最后,我将qryCumulativeLossesByMonth用作查询中的数据源,该查询将转换输出以匹配您请求的格式。
SELECt q.reportYear, MonthName(q.reportMonth) AS [Month], q.SumOfgainOrLoss AS Losses, q.SumOfgainOrLoss + IIf(q.PreviousGainOrLoss Is Null,0,q.PreviousGainOrLoss) AS CumFROM qryCumulativeLossesByMonth AS q;reportYear Month Losses Cum 2011 December $3,000.00 $3,000.00 2012 January $5,410.00 $8,410.00
您可能会使用子查询而不是单独的命名查询将其修改为单个查询。我使用了这种逐步的方法,因为我希望它会更容易理解。
编辑 :我用MonthName()函数返回了全名。如果您需要缩写的月份名称,请将True作为第二个参数传递给该函数。这些中的任何一个都可以工作:
MonthName(q.reportMonth, True) AS [Month]MonthName(q.reportMonth, -1) AS [Month]



