数据库中有以下记录: 
id     记账日期            会计科目(cCode)  借方发生额(cJf)  贷方发生额(cDf) 
1    2009-01-08            100201            500 
2    2009-01-08            100201            600 
3    2009-01-06            100201                              700 
4    2009-01-02            100201                              100 
要以记账日期查询财务帐簿的日记帐,生成以下的格式 
因为会计科目是银行存款科目,余额是在借方,他的公式是借方-贷方=余额 
要变成以下帐簿明细帐的格式: 
id   记账日期    会计科目(cCode)  借方发生额(cJf)  贷方发生额(cDf)  余额(cYf) 
4   2009-01-02    100201                         100             -100 
3   2009-01-06    100201                         700             -800 
1   2009-01-08    100201             500                         -300  
2   2009-01-08   100201              600                          300 
会计帐簿余额是每行进行借方-贷方产生的余额,请问这样的SQL语句该怎么写: 
select id,cDate,cCode,cJf,cDf from table1 
这样简单查询只能列出明细帐,看不到每笔记录的余额无法看到,请各位大侠帮忙指导,向这样的SQL语句该怎么写。谢谢! 

解决方案 »

  1.   

    create table tb(id int,记账日期 datetime,会计科目 varchar(10),借方发生额 int,贷方发生额 int) 
    insert into tb values(1 , '2009-01-08' , '100201' , 500 , null)
    insert into tb values(2 , '2009-01-08' , '100201' , 600 , null) 
    insert into tb values(3 , '2009-01-06' , '100201' , null, 700 )
    insert into tb values(4 , '2009-01-02' , '100201' , null, 100 )
    goselect m.id ,记账日期 ,m.会计科目 ,m.借方发生额 ,m.贷方发生额,
           余额 = (select sum(isnull(借方发生额,0) - isnull(贷方发生额,0)) from 
           (
             select * , px = (select count(1) from tb where 会计科目 = t.会计科目 and (记账日期 < t.记账日期 or (记账日期 = t.记账日期 and id < t.id))) + 1 from tb t
           ) n where n.会计科目 = m.会计科目 and n.px <= m.px )
    from
    (
      select * , px = (select count(1) from tb where 会计科目 = t.会计科目 and (记账日期 < t.记账日期 or (记账日期 = t.记账日期 and id < t.id))) + 1 from tb t
    ) m
    order by m.记账日期 , m.iddrop table tb/*
    id          记账日期                                                   会计科目       借方发生额       贷方发生额       余额          
    ----------- ------------------------------------------------------ ---------- ----------- ----------- ----------- 
    4           2009-01-02 00:00:00.000                                100201     NULL        100         -100
    3           2009-01-06 00:00:00.000                                100201     NULL        700         -800
    1           2009-01-08 00:00:00.000                                100201     500         NULL        -300
    2           2009-01-08 00:00:00.000                                100201     600         NULL        300(所影响的行数为 4 行)*/