期初金额:1000
发生额表:
     序号   提货金额     期末金额
     1      10            990
     2      20            970
     3      30            940
     4      10            930 
用sql 如何做,谢谢!

解决方案 »

  1.   

    create table tb(序号 int,提货金额 int,期末金额 int)
    insert into tb values(1 ,10 ,0)
    insert into tb values(2 ,20 ,0)
    insert into tb values(3 ,30 ,0)
    insert into tb values(4 ,10 ,0)
    godeclare @je as int
    set @je = 1000select 序号 ,提货金额 , 期末金额 = @je - (select sum(提货金额) from tb where 序号 <= t.序号) from tb tdrop table tb /*序号          提货金额        期末金额        
    ----------- ----------- ----------- 
    1           10          990
    2           20          970
    3           30          940
    4           10          930(所影响的行数为 4 行)
    */
      

  2.   

    declare @cq as int
    set @cq = 1000select t.序号 ,t.提货金额 , 期末金额 =1000-SUM(k.提货金额)
    from tb t join tb k on  k.序号 <= t.序号
    group by t.序号 ,t.提货金额 
    order by t.序号
    /*
    序号          提货金额        期末金额
    ----------- ----------- -----------
    1           10          990
    2           20          970
    3           30          940
    4           10          930*/
      

  3.   

    create table tb(序号 int,提货金额 int,期末金额 int,类型 varchar(10))
    insert into tb values(1 ,10 ,0,'提货')
    insert into tb values(2 ,20 ,0,'提货')
    insert into tb values(3 ,30 ,0,'提货')
    insert into tb values(4 ,10 ,0,'提货')
    insert into tb values(5 ,20 ,0,'回款')
    insert into tb values(6 ,10 ,0,'提货')
    go
    declare @cq as int
    set @cq = 1000select t.序号 ,t.提货金额 , 期末金额 =1000+SUM(case when k.类型='提货' then -k.提货金额 else k.提货金额 end)
    from tb t join tb k on  k.序号 <= t.序号
    group by t.序号 ,t.提货金额 
    order by t.序号drop table tb 
    /*
    序号          提货金额        期末金额
    ----------- ----------- -----------
    1           10          990
    2           20          970
    3           30          940
    4           10          930
    5           20          950
    6           10          940*/
    LZ最后一行结果有误
      

  4.   

    create table tb(序号 int,提货金额 int,期末金额 int,类型 varchar(10))
    insert into tb values(1 ,10 ,0,'提货')
    insert into tb values(2 ,20 ,0,'提货')
    insert into tb values(3 ,30 ,0,'提货')
    insert into tb values(4 ,10 ,0,'提货')
    insert into tb values(5 ,20 ,0,'回款')
    insert into tb values(6 ,10 ,0,'提货')godeclare @je as int
    set @je = 1000select 序号 ,提货金额 ,类型, 期末金额 = @je - (select sum(case when 类型 = '提货' then 提货金额 else -提货金额 end) from tb where 序号 <= t.序号) from tb tdrop table tb /*序号          提货金额        类型         期末金额        
    ----------- ----------- ---------- ----------- 
    1           10          提货         990
    2           20          提货         970
    3           30          提货         940
    4           10          提货         930
    5           20          回款         950
    6           10          提货         940(所影响的行数为 6 行)*/