
数据结构如上图
想要的结果如下
ByYearMonth RScore
200001 17.80
200002 17.80
200003 17.80
200004 17.80
200005 17.80
200006 17.80
200007 17.80
200008 17.80
200009 19.80
200012 26.55
......
至今月份
一直累加计算下来至今,平时sql写的较少,跟大神们学习了~
SQL
------解决方案--------------------
declare @begindate datetime ----开始日期
declare @enddate datetime ----结束日期
set @begindate = '2000-1-01'
set @enddate = '2013-04-01'
;with ta1 as (
select cast( @begindate as datetime) as ByYearMonth
union all
select dateadd(month,1, ta1.ByYearMonth) from ta1 where ta1.ByYearMonth < @enddate
) ,ta2 as (
select convert(nvarchar(6),ta1.ByYearMonth,112) as ByYearMonth from ta1
) ---------递归整个时间段
,ta3 as (
select ta2.ByYearMonth,isnull(你的表名.Rscore,0) as Rscore from ta2
left join 你的表名 on 你的表名.ByYearMonth = ta2.ByYearMonth
)--------整个时间段做关联你的表
select aa.ByYearMonth,sum(ta3.Rscore) from ta3 inner join ta3 aa on ta3.ByYearMonth<= aa.ByYearMonth
group by aa.ByYearMonth -----在自关联累加
option (maxrecursion 30000)
应该没有什么问题,意思就这样