2014-09-19 66 views
3

TakenOn是日期時間列累積總和在SQL中,在日期的情況下

隨着該過程,

;WITH TBL AS 
    (SELECT CONVERT(date,TakenOn) AS Date, 
      COUNT(*) AS 'NewSubs' 
    FROM Urls (NOLOCK) 
    WHERE FId = 11 
    AND (TakenOn >= @StartDate) 
    AND (TakenOn <= @EndDate) 
    GROUP BY CONVERT(date,TakenOn)) 
SELECT t1.Date, t1.NewSubs, 
       SUM(t1.NewSubs) AS 'TotalSubs' 
FROM TBL t1 
INNER JOIN TBL t2 ON t1.Date >= t2.Date 
GROUP BY t1.Date, t1.NewSubs 

輸出爲://(這是錯誤的,我)

Date  NewSubs TotalSubs 
2014-09-19 2  2 
2014-09-20 3  6 
2014-09-21 1  3 
2014-09-22 4  16 

我該怎麼改變輸出爲

Date  NewSubs TotalSubs 
2014-09-19 2  2 
2014-09-20 3  5 
2014-09-21 1  6 
2014-09-22 4  10 

回答

3

試試這個:SUM(t1.NewSubs) over(order by t1.Date)

例如:

;WITH TBL AS 
    (SELECT CONVERT(date,TakenOn) AS Date, 
      COUNT(*) AS 'NewSubs' 
    FROM Urls (NOLOCK) 
    WHERE FId = 11 
    AND (TakenOn >= @StartDate) 
    AND (TakenOn <= @EndDate) 
    GROUP BY CONVERT(date,TakenOn)) 
SELECT t1.Date, t1.NewSubs, 
       SUM(t1.NewSubs) over(order by t1.Date) AS 'TotalSubs' 
FROM TBL t1 
INNER JOIN TBL t2 ON t1.Date >= t2.Date 
GROUP BY t1.Date, t1.NewSubs 
+1

謝謝你這麼多多納爾... – Qwerty 2014-09-19 16:22:02