insert #x
select
10 , 100 , 1
union all
select
20 , 1200 , 1
union all
select
30 , 800 , 1
union all
select
10 , 2000 , 2
union all
select
20 , 1000 , 2
union all
select
10 , 1100 , 3
union all
select
30 , 1600 , 3
union all
select
20 , 2100 , 4
union all
select
30 , 1800 , 4
union all
select
10 , 1000 , 5
union all
select
20 , 2000 , 5
union all
select
30 , 1500 , 5
union all
select
10 , 3000 , 6
union all
select
20 , 1000 , 6
union all
select
30 , 1600 , 6
go
select 地方代码,各地当月费用,月份,
(select sum(各地当月费用) from #x where 地方代码=a.地方代码 and 月份<=a.月份) as 各地全年总费用
from #x a
order by 地方代码,月份
select *,
(select sum(各地当月费用) from #a where 地方代码=aa.地方代码
-------^^^^^^^^^^^^^^^^这里是求和-------^^^^^^^^^^里面的代码和外面的代码字段相同的
and 月份<=aa.月份)
----^^^^^^^^^^^^如果你只是要相对的全年,就必须加这个,
----意思也是里面的字查询的月份必须小于等于外面的月份
select 地方代码,各地当月费用,月份,
(select sum(各地当月费用) from tablename where 地方代码=a.地方代码 and 月份<=a.月份) as 各地全年总费用
from tablename a
order by 地方代码,月份
这样的写法和select 地方代码,各地当月费用,月份,
(select sum(各地当月费用) from tablename ) as 各地全年总费用
from tablename
order by 地方代码,月份 是一样的,就是10000了就是全部的总和了