select line,qty,qty1,qty-qty1 qty2 from table1 order by line

解决方案 »

  1.   

    select line,qty,qty1 ,0 as qty2 into #tmp from table1 order by line
    declare @i int
    set @i=0
    update table1 set qty2=qty-qty1-@i,@i=@i+qty1
    select * from #tmp
      

  2.   

    可能是我描述的不大明白,qty的值不会变的,一直是100,每行都要把以前减过的qty1减掉
      

  3.   

    select a.line,
           a.qty,
           a.qty1,
           qty2 = a.qty - (select IsNull(sum(qty1),0) from @t where line <= a.line)
    from @t a
      

  4.   

    --测试环境
    declare @t table(line varchar(2),qty decimal(5,2),qty1 decimal(5,2))
    insert into @t select '2',100,55
    union all select '5',100,10
    union all select '6',100,22
    union all select '8',100,35
    --查询
    select line,
           qty,
    qty1,
    qty2=qty-(select sum(qty1) from @t where line<=a.line)
    from @t a
    --结果
    line qty     qty1    qty2                                     
    ---- ------- ------- ---------------------------------------- 
    2    100.00  55.00   45.00
    5    100.00  10.00   35.00
    6    100.00  22.00   13.00
    8    100.00  35.00   -22.00(所影响的行数为 4 行)