求这样一个查询语句,该如何处理
求这样一个查询语句
------解决方案--------------------
select [月份],[科目],[本月数],sum(a.[本月数])
from tb a
where exists(
select top(1)1 from tb b where a.[科目]=b.[科目] and a.[月份]<=b.[月份])
group by [月份],[科目],[本月数]
------解决方案--------------------
表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.本月数