2015-01-09 103 views
1

我在我的Access數據庫中運行SQL查詢以累積我在每條記錄之後運行的距離。SQL計算運行

我用下面的代碼來計算運行總計:

SELECT a.run, a.year, a.date, a.distance, round((SELECT SUM(b.distance) 
         FROM vwAllCast b 
         WHERE b.run <= a.run),1) AS AccDistance 
FROM vwAllCast AS a 
ORDER BY a.run DESC; 

此代碼返回所有的記錄總結在AccDistance所有距離。現在,我想每年都重新進行一次積累。有沒有人有一個想法如何實現?

+2

只需添加where子句過濾recrods – HaveNoDisplayName

+0

或者按年分組,以獲得同一查詢結果中的所有年份 –

回答

0

一樣的Piyush說,我覺得這樣的事情應該工作:

SELECT a.run, a.year, a.date, a.distance, round((SELECT SUM(b.distance) 
         FROM vwAllCast b 
         WHERE b.run <= a.run and a.year = b.year),1) AS AccDistance 
FROM vwAllCast AS a 
ORDER BY a.run DESC; 
+0

Ahh擊敗了我:) –

+1

感謝FuzzyTree和Aramillo,buth查詢的工作非常漂亮。自我加入和分組速度要快一點。 –

0

自由可能比相關子查詢更快加入+組

SELECT a.run, a.year, a.date, a.distance, SUM(b.distance) 
FROM vwAllCast AS a 
JOIN vwAllCast b on b.run <= a.run AND b.year = a.year 
GROUP BY a.run, a.year, a.date, a.distance 
ORDER BY a.run DESC