select
    期初库存=isnull((select sum(发生数量) from 表 where 发生时间<a.发生时间),0),
    a.发生业务,
    a.发生数量,
    a.发生时间,
    期末库存=(select sum(发生数量) from 表 where 发生时间<=a.发生时间)
from
    表 a
order by
    a.发生时间

解决方案 »

  1.   

    select id=identity(int,1,1),* into #t from  表select
        期初库存=isnull((select sum(发生数量) from 表 where id<a.id),0),
        a.发生业务,
        a.发生数量,
        a.发生时间,
        期末库存=(select sum(发生数量) from 表 where id<=a.id)
    from
        表 a
    order by
        a.id---思路不变,加一个id列,如果发生时间是一个完整的时间也不会有问题的
      

  2.   

    TO:  wangdehao(找找找)
    试过了,还是不行
      

  3.   

    --麻烦点
    set nocount on
    declare @a table(发生业务 varchar(10),发生数量 int,发生时间 char(10))insert @a select '进货',10 ,'2003/02/05'
    insert @a select '销售',-5 ,'2003/02/08'
    insert @a select '进货',20 ,'2003/02/10'
    insert @a select '进货',5  ,'2003/02/15'
    insert @a select '销售',-15,'2003/02/18'declare @b table(id int identity(1,1),期初库存 int,发生业务 varchar(10),发生数量 int,发生时间 char(10),期末库存 int)
    insert @b(发生业务,发生数量,发生时间) select 发生业务,发生数量,发生时间 from @a order by 发生时间
    update @b set 期初库存=0,期末库存=发生数量 where id=1
    update @b set 期初库存=(select 期末库存 from @b where id=1) where id=2declare @i int
    set @i=2
    while @i<=(select max(id) from @b) begin
    update @b set 期末库存=期初库存+发生数量 where id=@i
    update @b set 期初库存=(select 期末库存 from @b where id=@i) where id=@i+1
    set @i=@i+1
    end
    set nocount off
    select 期初库存,发生业务,发生数量,发生时间,期末库存 from @b/*结果
    期初库存   发生业务       发生数量    发生时间    期末库存        
    ----------- ---------- -----------  ---------- ----------- 
    0           进货         10          2003/02/05 10
    10          销售         -5          2003/02/08 5
    5           进货         20          2003/02/10 25
    25          进货         5           2003/02/15 30
    30          销售         -15         2003/02/18 15(所影响的行数为 5 行)
    */
      

  4.   

    select identity(int,1,1) as id,* into #T from 表select
        期初库存=isnull((select sum(发生数量) from #T where 发生时间<=a.发生时间 and id<a.id),0),
        a.发生业务,
        a.发生数量,
        a.发生时间,
        期末库存=(select sum(发生数量) from #T where 发生时间<=a.发生时间 and id<=a.id)
    from
        #T a
    order by
        a.发生时间drop table #T
      

  5.   

    wangdehao(找找找) 
    =========================加一个id列,如果发生时间是一个完整的时间也不会有问题的,为什么???????????????
      

  6.   


    set nocount on
    declare @a table(发生业务 varchar(10),发生数量 int,发生时间 char(20))insert @a select '进货',10 ,'2003-02-05'
    insert @a select '销售',-5 ,'2003-02-08 15:15:00'
    insert @a select '进货',20 ,'2003-02-08 09:00:00'
    insert @a select '进货',5  ,'2003-02-08 12:00:00'
    insert @a select '销售',-15,'2003-02-18'select identity(int,1,1) as id,* into #T from @a order by 发生时间select
        期初库存=isnull((select sum(发生数量) from #T where 发生时间<=a.发生时间 and id<a.id),0),
        a.发生业务,
        a.发生数量,
        a.发生时间,
        期末库存=(select sum(发生数量) from #T where 发生时间<=a.发生时间 and id<=a.id)
    from
        #T a
    order by
        a.发生时间drop table #T