select 地方代码,各地当月费用,月份,
(select sum(各地当月费用) from tablename where 地方代码=a.地方代码 and 月份<=a.月份) as 各地全年总费用
from tablename a
order by 地方代码,月份注意:表结构使得这个查询不能跨年
(select sum(各地当月费用) from tablename where 地方代码=a.地方代码 and 月份<=a.月份) as 各地全年总费用
from tablename a
order by 地方代码,月份注意:表结构使得这个查询不能跨年
在你的库中运行一下,看看结果。
(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了就是全部的总和了
insert #a values(10, 1000 , 5 )
insert #a values(20 , 2000 , 5 )
insert #a values(30 , 1500 , 5 )
select *,(select sum(各地当月费用) from #a where 地方代码=aa.地方代码) 各地全年总费用 from #a aa order by 地方代码go
drop table #a
insert #a values(10, 1000 , 5 )
insert #a values(20 , 2000 , 5 )
insert #a values(30 , 1500 , 5 )
select *,(select sum(各地当月费用) from #a where 地方代码=aa.地方代码 and 月份<=aa.月份) 各地全年总费用 from #a aa order by 地方代码go
drop table #a
(select sum(各地当月费用) from #a where 地方代码=aa.地方代码
-------^^^^^^^^^^^^^^^^这里是求和-------^^^^^^^^^^里面的代码和外面的代码字段相同的
and 月份<=aa.月份)
----^^^^^^^^^^^^如果你只是要相对的全年,就必须加这个,
----意思也是里面的字查询的月份必须小于等于外面的月份 各地全年总费用 from #a aa order by 地方代码
goinsert #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 , 6goselect 地方代码,各地当月费用,月份,
(select sum(各地当月费用) from #x where 地方代码=a.地方代码 and 月份<=a.月份) as 各地全年总费用
from #x a
order by 地方代码,月份结果:地方代码 各地当月费用 月份 各地全年总费用
----------- ----------- ----------- -----------
10 100 1 100
10 2000 2 2100
10 1100 3 3200
10 1000 5 4200
10 3000 6 7200
20 1200 1 1200
20 1000 2 2200
20 2100 4 4300
20 2000 5 6300
20 1000 6 7300
30 800 1 800
30 1600 3 2400
30 1800 4 4200
30 1500 5 5700
30 1600 6 7300 (所影响的行数为 15 行)