select 编码,年度,上年=(select sum(isnull(拨款,0)-isnull(花费,0)) from 临时表 where 编码=a.编码 and 年度<a.年度)
,拨款,花费,余额=(select sum(isnull(拨款,0)-isnull(花费,0)) from 临时表 where 编码=a.编码 and 年度<=a.年度)
from 临时表 a order by 编码,年度

解决方案 »

  1.   

    select 编码,年度,上年=isnull((select sum(isnull(拨款,0)-isnull(花费,0)) from 临时表 where 编码=a.编码 and 年度<a.年度),0)
    ,拨款,花费,余额=(select sum(isnull(拨款,0)-isnull(花费,0)) from 临时表 where 编码=a.编码 and 年度<=a.年度)
    from 临时表 a order by 编码,年度
      

  2.   

    create table 临时表
    (年度 int,编码 varchar(10),拨款 numeric(18,2), 花费 numeric(18,2))
    年度  编码  上年结余   拨款      花费    余额
    select 年度,
           编码,
          上年结余=isnull((select sum(拨款-花费) 
                           from 临时表 
                           where 年度<a.年度 and 编码=a.编码),0),
          拨款,
          花费,
          余额=(select sum(拨款-花费) 
                from 临时表 
                where 年度<=a.年度 and 编码=a.编码)
    from 临时表 a
      

  3.   

    select 年度,
           编码,
          上年结余=isnull((select sum(拨款-花费) 
                           from 临时表 
                           where 年度<a.年度 and 编码=a.编码),0),
          拨款,
          花费,
          余额=(select sum(拨款-花费) 
                from 临时表 
                where 年度<=a.年度 and 编码=a.编码)
    from 临时表 a
      

  4.   

    select 年度,编码,上年余=isnull((select 拨款-花费 from 临时表 where 年度=(a.年度-1) and 编码=a.编码),0),拨款,花费,拨款-花费 as 余额
    from 临时表 a