TakenOn是日期时间列
使用
程序;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
答案 0 :(得分: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