日期:2014-05-17  浏览次数:20539 次

求这样一个查询语句
表A
月份  科目     本月数    
1     6001      10        
1     6002      15
1     6003      20
2     6001       6      
2     6002       5
3     6002      10
3     6003       8
要求显示结果
月份   科目     本月数    累计数
1     6001      10         10      
1     6002      15         15
1     6003      20         20
2     6001       6         16      
2     6002       5         20
2     6003       0         20
3     6001       0         16      
3     6002       5         25

------解决方案--------------------
select [月份],[科目],[本月数],sum(a.[本月数]) 
from tb a
where exists(
  select top(1)1 from tb b where a.[科目]=b.[科目] and a.[月份]<=b.[月份])
group by [月份],[科目],[本月数]
------解决方案--------------------

with a (
月份 , 科目  ,   本月数 )as(   
select 1,     6001 ,     10 union all        
select 1,     6002 ,     15 union all
select 1,     6003 ,     20 union all
select 2,     6001 ,      6 union all      
select 2,     6002 ,      5 union all
select 3,     6002 ,     10 union all
select 3,     6003 ,      8)
,b as(
select a.月份,a.