当前位置: 代码迷 >> Sql Server >> 关于SQL SEVER累加的有关问题
  详细解决方案

关于SQL SEVER累加的有关问题

热度:67   发布时间:2016-04-27 14:15:27.0
关于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 t346select '2011-1-1', 98 union allselect '2011-1-25', 10 union all  select '2011-2-3', 13 union allselect '2011-3-5', 4select a.年月,(select isnull(sum(货物数量),0) from t346 b where b.年月<convert(date,a.年月+'-01')) 货物数量from (select distinct left(convert(varchar(12),年月,23),7) 年月 from t346union allselect left(convert(varchar(12),dateadd(m,1,max(年月)),23),7) from t346) a年月           货物数量------------ -----------2011-01        02011-02        1082011-03        1212011-04        125(4 row(s) affected)
  相关解决方案