当前位置: 代码迷 >> Sql Server >> 请问数据累加有关问题
  详细解决方案

请问数据累加有关问题

热度:75   发布时间:2016-04-24 21:57:35.0
请教数据累加问题
我要做一个报表,输入开始、结束日期后,返回按月排序的数据金额,能不能实现每个月后面加一项累计金额,比如
我输入开始日期 2013-01 结束日期 2013-03 出来
月份    金额       累计金额
1     20000     20000
2     30000     50000
3      5000     55000
这样的,累计金额不必去数据库中查找,只要前项累加
报表

------解决方案--------------------

with tb(月份,金额)as(
select 1,20000 union all
select 2,30000 union all
select 3,5000
)
select *,( 
select SUM(a.金额) from tb a,tb b 
where a.月份<=b.月份 and b.月份=c.月份
group by b.月份) 累计金额
from tb c

用视图吧..
------解决方案--------------------
with tb(月份,金额)as(
select 1,20000 union all
select 2,30000 union all
select 3,5000
)
select 月份,金额,(select sum(金额) from tb t2 where t2.月份<=t1.月份) 累计金额
from
tb t1
  相关解决方案