2014-01-23 57 views
1

我不是一個很大的Access風扇,但是對於這個項目,我被要求創建一個Access數據庫。我爲其他數據庫類型創建了類似的東西,所以它不是太困難。我大部分都想出來了,但運行總數卻讓我頭腦發熱。MS Access 2010在查詢中運行總計

我有如下表:表名attendanceView

查詢:SELECT * FROM attendanceView

====================================================================================== 
agentID |  incurrredDate  | points | OneFallOff  | TwoFallOff 
====================================================================================== 
chtall  |  10/7/2013  |  2  |  2   |  2 
chtall  |  10/15/2013  |  2  |  2   |  2 
chtall  |  11/26/2013  |  2  |  2   |  2 
chtall  |  12/17/2013  |  2  |  2   |  2 
vimunson |  7/22/2013  |  2  |  2   |  2 
vimunson |  7/29/2013  |  2  |  1   |  1 
vimunson |  12/6/2013  |  1  |  1   |  1 

這個查詢做的事情需要做,找到值OneFallOffTwoFallOff。不過,我需要找到一種方法來爲每個agentID運行總計TwoFallOff。例如chtall有四條記錄,下面看到的,這一點,應該是什麼樣子:

================================================================================================== 
agentID |  incurrredDate  | points | OneFallOff  | TwoFallOff  | total 
================================================================================================== 
chtall  |  10/7/2013  |  2  |  2   |  2   | 2 
chtall  |  10/15/2013  |  2  |  2   |  2   | 4 
chtall  |  11/26/2013  |  2  |  2   |  2   | 6 
chtall  |  12/17/2013  |  2  |  2   |  2   | 8 
vimunson |  7/22/2013  |  2  |  2   |  2   | 2 
vimunson |  7/29/2013  |  2  |  1   |  1   | 3 
vimunson |  12/6/2013  |  1  |  1   |  1   | 4 

我已經試過DSUM()沒有工作,也許我用錯了。如果表中不清楚,代理更改時,total列將重置爲0。

回答

6

你可以用相關的子查詢得到你想要的。

SELECT 
    a1.agentID, 
    a1.incurrredDate, 
    a1.points, 
    a1.OneFallOff, 
    a1.TwoFallOff 
    (
     SELECT Sum(a2.TwoFallOff) 
     FROM attendanceView AS a2 
     WHERE 
       a2.agentID = a1.agentID 
      AND a2.incurrredDate <= a1.incurrredDate 
    ) AS total 
FROM attendanceView AS a1; 

你也可以用DSum做到這一點,但你需要在DSumWhereCondition選項可以使用分隔符與agentIDincurrredDate。看起來更加努力,而且我發現它比子查詢方法更容易出錯。

SELECT 
    a.agentID, 
    a.incurrredDate, 
    a.points, 
    a.OneFallOff, 
    a.TwoFallOff, 
    DSum 
     (
      "TwoFallOff", "attendanceView", 
      "agentID = '" & a.agentID & "' " & 
      "AND incurrredDate <= " & 
      Format(a.incurrredDate, "\#yyyy-m-d\#") 
     ) AS total 
FROM attendanceView AS a; 

兩個查詢返回使用您的樣本數據的請求的結果在Access 2007

+0

當我在訪問2016運行的一個代碼塊,我得到以下錯誤:「無效的參數功能」。看起來變量a1不能從子查詢中得到(所以不在其範圍內) – Ruut

+0

問題在'FROM attendanceView AS a1'後添加'ORDER BY a1.incurredDate'時解決了。 – Ruut