期初: 科目 金额  
       库存  100  
凭证表 摘要  借方 贷方 金额
      XX领入 库存 领入 10 
      XX发出 发出 库存 5 
账簿 年 月 日 字 号 摘要 借方 贷方 方向 金额 余额
                    期初 库存       借  100  100
    2012 1 1 记 1 XX领入 库存       借  10   110
    2012 1 1 记 2 XX发出      库存  贷  5    105
-----------------------------------------------------------------
以上为正常的数据 现在的问题是 我的余额计算不对 只能计算单行的 特此求助诸位大神帮忙 
账簿生成是临时表 从凭证表抓取的数据 并计算余额生成的  

解决方案 »

  1.   


    --> 测试数据:[tbl]
    go
    if object_id('[tbl]') is not null 
    drop table [tbl]
    go
    create table [tbl](
    [name] varchar(1),
    [date] varchar(5),
    [num] int
    )
    go
    insert [tbl]
    select 'a','1-1号',1 union all
    select 'b','1-2号',4 union all
    select 'a','1-3号',8 union all
    select 'a','1-4号',5 union all
    select 'b','1-5号',6 union all
    select 'b','1-6号',9;with t
    as(
    select ROW_NUMBER()over(partition by name
    order by [date]) as id,
    *,num  as total from tbl
    ),
    m as(
    select id,name,[date],num,total from t where id=1
    union all
    select a.id,a.name,a.[date],a.num,b.total+a.num from t a
    inner join m b on a.id=b.id+1 and a.name=b.name
    )
    select name,[date],num,total from m order by name/*
    name date num total
    a 1-3号 8 8
    a 1-4号 5 13
    a 1-1号 1 14
    b 1-2号 4 4
    b 1-5号 6 10
    b 1-6号 9 19
    */
    类似问题