日期:2014-05-18  浏览次数:20775 次

关于SQL SEVER累加的问题
我有一个表
年月 货物数量  
2011-1-1 98
2011-1-25 10 
2011-2-3 13
2011-3-5 4

我想显示成为

年月 货物数量
2011-1 0
2011-2 108
2011-3 121
2011-4 125

意思就是2011-1月份统计的是1月份之前的所有货物数量,2011-2月份统计的是2月份之前的所有货物数量,以此类推,请问下这句SQL语句该怎么写啊

------解决方案--------------------
SQL code

create table t346
(年月 date, 货物数量 int)

insert into t346
select '2011-1-1', 98 union all
select '2011-1-25', 10 union all  
select '2011-2-3', 13 union all
select '2011-3-5', 4


select a.年月,
(select isnull(sum(货物数量),0) 
from t346 b where b.年月<convert(date,a.年月+'-01')) 货物数量
from 
(
select distinct left(convert(varchar(12),年月,23),7) 年月 from t346
union all
select left(convert(varchar(12),dateadd(m,1,max(年月)),23),7) from t346
) a

年月           货物数量
------------ -----------
2011-01        0
2011-02        108
2011-03        121
2011-04        125

(4 row(s) affected)