我在你的問題的編輯歷史記錄中發現了表和字段名,所以使用了th這個答案中的名字。您沒有提供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 SumOfgainOrLoss
FROM record_matYields AS y
GROUP BY
Year(reportDate),
Month(reportDate);
reportYear reportMonth MinOfreportDate SumOfgainOrLoss
2011 12 12/28/2011 $3,000.00
2012 1 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 PreviousGainOrLoss
FROM qryMonthlyLosses AS q;
reportYear reportMonth MinOfreportDate SumOfgainOrLoss PreviousGainOrLoss
2011 12 12/28/2011 $3,000.00
2012 1 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 Cum
FROM 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]
的MS Access本身不支持查詢此功能。 [這是一個解釋如何實現的例子。](http://msaccess.blogspot.com/2006/01/how-to-create-running-totals-in-query.html)FWIW,Oracle提供了一種本地方式做總計; [這裏是一個例子](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1793764100346222947)。 –