在SQL Server 2008中,如果我有这样的表。
Date NoOfCases
--------------------
2013-11-27 1
2013-11-28 2
2013-11-29 1
2013-11-30 3
我希望将前一笔加到下一行的值中。这意味着输出应该是这样的:
Date AccumulatedNoOfCases
2013-11-27 1
2013-11-28 3
2013-11-29 4
2013-11-30 7
有什么建议吗?提前谢谢。
答案 0 :(得分:2)
你可以在同一张桌子上进行连接,日期更小或相等。
select t1.date, sum(t2.NoOfCases) as AccumulatedNoOfCases
from Table1 t1
join Table1 t2 on t2.Date <= t1.Date
group by t1.date
有了计数,我会使用简洁的cte
with cnt as (select date, count(*) as cnt from Table1
group by date)
select t1.date, sum(t2.cnt) as AccumulateNoOfCases
FROM cnt t1
join cnt t2 on t2.date <=t1.date
group by t1.date;
请参阅SqlFiddle
使用您的数据,应该是这样的。
WITH cte as
(select [Date of hospital visit]) as dte, count(*) as cnt
FROM DW_Epidemic_Warning
GROUP BY [Date of hospital visit])
select t1.dte, sum(t2.cnt) as AccumulateNoOfCases
FROM cte t1
join cte t2 on t2.dte <=t1.dte
group by t1.dte;
答案 1 :(得分:1)
您没有说明您正在使用的SQL Server版本。如果是2012年,您可以执行类似
的操作SELECT
t1.date, sum(t1.NoOfCases) OVER (ORDER BY t1.date) AS AccumulatedNoOfCases
FROM Table1 t1
答案 2 :(得分:0)
我喜欢这个:
Select c.CaseDate,
(Select Sum(NoOfCases)
From Cases
Where CaseDate <= c.CaseDate
AND CaseDate > '2013-11-20') AS AccumulatedCases
From Cases c
显然AND CaseDate > '2013-11-20'
在这种情况下完全是任意的;你可能想在那里使用一个参数。