select *,结存=0 into #t
from 表 adeclare @i int
set @i=50
update #t set @i=@i+isnull(本期进,0)-isnull(本期出,0),结存=@iselect * from #t

解决方案 »

  1.   

    --测试--测试数据
    create table 表(编码 char(4),本期进 int,本期出 int)
    insert 表 select '0001',10  ,null
    union all select '0001',null,20
    union all select '0001',30  ,null
    go--查询处理
    select *,结存=0 into #t
    from 表 adeclare @i int
    set @i=50
    update #t set @i=@i+isnull(本期进,0)-isnull(本期出,0),结存=@iselect * from #tdrop table #t
    go--删除测试
    drop table 表/*--测试结果
    编码   本期进         本期出         结存          
    ---- ----------- ----------- ----------- 
    0001 10          NULL        60
    0001 NULL        20          40
    0001 30          NULL        70(所影响的行数为 3 行)
    --*/
      

  2.   


    select 编码, 
           上期结余, 
           sum(isnull(本期进,0)-isnull(本期出,0))+上期结余 as 结存 
    from tablename
    group by 编码, 上期结余
    要输出你所要求的格式,还应该有个“发生时间”字段。 
      

  3.   

    to victorycyz(中海):
    只得到合计数,只有一条记录啊
    to zjcxc(邹建) :
    谢谢!
    第一个答案是正确的,您没看走眼,其末结存是50,期初应是30
    难道只能用临时表吗?这样是不是速度慢!
    请教