歪了没对正 
日  期        客户      销售      收款     欠款
             期初欠款                     100
2005-1-5        aaa     10                110   
2005-1-10       aaa     20                130 
2005-1-12       aaa               30      100
2005-1-15       aaa     40                140
2005-1-20       aaa               50       90
               合计     70        80       90 

解决方案 »

  1.   

    Create table b1(客户 varchar(20),期初欠款 money)
    go
    Insert b1
    select 'aaa',100
    goCreate table b2(日期 datetime,客户 varchar(20), 销售 money,收款 money)
    Insert into b2 
          select '2005-1-5','aaa',   10,null
    union select '2005-1-10','aaa',  20,null
    union select '2005-1-12','aaa',  null,30
    union select '2005-1-15','aaa',  40 ,null
    union select '2005-1-20','aaa',  null,50
    go
    Select a.日期,b.客户,a.销售,a.收款,欠款=
        期初欠款+(select sum(isNULL(销售,0) 
                  -isNULL(收款,0)) from b1
                  inner join b2 on b1.客户=b2.客户
                  Where b2.日期<=a.日期 ) into #t
    from b2 a inner join b1 b on a.客户=b.客户select 日期=isNULL(convert(varchar(10),日期,120),''),
           客户=isNULL(客户,''),销售=isNULL(cast(销售 as varchar(10)),''),
           收款=isNULL(cast(收款 as varchar(10)),''),
           欠款=isNULL(cast(欠款 as varchar(10)),'') 
    from ( select NULL 日期,'期初欠款' 客户,NULL 销售,
          NULL 收款,期初欠款 欠款,1 as no 
           from b1
            union
    select 日期,客户,销售,收款,欠款,2 as no from #t
    union 
    select NULL 日期,'合计' 客户,sum(销售) 销售,
                   sum(收款) 收款,
              (select top 1 欠款 from #t order by 日期 desc) 欠款,3 as no
    from #t ) x order by nodrop table #t
    go
    drop table b1
    drop table b2
      

  2.   

    理解上应该 把
    收款=isNULL(cast(收款 as varchar(10)),''),
    改成
    收款=isNULL(cast(收款 as money),''),因为 '收款' 不应该是 varchar