首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求这么一个查询语句

2013-06-19 
求这样一个查询语句表A月份科目本月数1600110160021516003202600162600253600210360038要求显示结果月份科

求这样一个查询语句

表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.科目,isnull(b.本月数,0)本月数 


from (select distinct a.月份,b.科目  from a,a b)a  left join a b
on a.月份=b.月份 and a.科目=b.科目)
select b.月份,b.科目,b.本月数,SUM(c.本月数)累积数 
from b,b c where b.科目=c.科目 and b.月份>=c.月份
group by b.月份,b.科目,b.本月数

热点排行
Bad Request.