select *,期末余额=(select sum(本期应收-本期应付) from 表 where 客户代码=a.客户代码 and 单据日期<=a.单据日期)
from 表 a

解决方案 »

  1.   

    --测试--测试数据
    create table 表(客户代码 varchar(10),客户名称 varchar(10),单据日期 datetime,本期应收 int,本期应付 int)
    insert 表 select '01','北京','2004-1-1',1000,0
    union all select '01','北京','2004-2-1',100 ,0
    union all select '01','北京','2004-3-1',0   ,200
    union all select '01','北京','2004-4-1',500 ,200
    union all select '01','北京','2004-5-1',500 ,0
    union all select '02','上海','2004-1-1',0   ,2000
    union all select '02','上海','2004-2-1',100 ,0
    union all select '02','上海','2004-3-1',0   ,200
    union all select '02','上海','2004-4-1',500 ,200
    union all select '02','上海','2004-5-1',500 ,0
    go--查询
    select *,期末余额=(select sum(本期应收-本期应付) from 表 where 客户代码=a.客户代码 and 单据日期<=a.单据日期)
    from 表 a
    go--删除测试
    drop table 表/*--测试结果客户代码       客户名称   单据日期           本期应收   本期应付    期末余额  
    ---------- ------ ------------------------- --------- ----------- -------- 
    01         北京     2004-01-01 00:00:00.000  1000      0           1000
    01         北京     2004-02-01 00:00:00.000  100       0           1100
    01         北京     2004-03-01 00:00:00.000  0         200         900
    01         北京     2004-04-01 00:00:00.000  500       200         1200
    01         北京     2004-05-01 00:00:00.000  500       0           1700
    02         上海     2004-01-01 00:00:00.000  0         2000        -2000
    02         上海     2004-02-01 00:00:00.000  100       0           -1900
    02         上海     2004-03-01 00:00:00.000  0         200         -2100
    02         上海     2004-04-01 00:00:00.000  500       200         -1800
    02         上海     2004-05-01 00:00:00.000  500       0           -1300(所影响的行数为 10 行)
    --*/
      

  2.   

    多谢zjcxc(邹建)大哥
    这边我想补充问一下,如果没有那个'单据日期'字段
    还有办法吗?
      

  3.   

    zjcxc(邹建)大哥
    where r u