查询在Oracle中打开和关闭余额

时间:2014-01-29 05:37:09

标签: sql oracle oracle11g oracle10g

嗨我有以下表和数据来获得每个账户期初余额所需的开仓和收盘余额gdate< 02-oct-2013这里是我的表

create table ledger (account_no varchar2(10),gdate date,debit number(8),credit number(8))

insert into ledger (account_no,gdate,debit,credit) values ('10-0001','01-oct-2013',1000,0);
insert into ledger (account_no,gdate,debit,credit) values ('10-0001','24-oct-2013',0,440);
insert into ledger (account_no,gdate,debit,credit) values ('20-0001','01-oct-2013',3000,0);
insert into ledger (account_no,gdate,debit,credit) values ('30-0001','01-oct-2013',300,0);
insert into ledger (account_no,gdate,debit,credit) values ('20-0001','16-oct-2013',1200,0);
insert into ledger (account_no,gdate,debit,credit) values ('30-0001','17-oct-2013',0,1340);
insert into ledger (account_no,gdate,debit,credit) values ('30-0001','24-oct-2013',500,0);

我需要以下结果

ACCOUNT_NO OPENING  DEBIT  CREDIT  CLOSING
10-0001    1000    0       440    560
20-0001    3000    1200      0    4200
30-0001     300    500    1340    540

2 个答案:

答案 0 :(得分:1)

试试这个:

with tab as (select l.*,
                    dense_rank() over (partition by l.account_no order by l.gdate) min_date
               from ledger l),
tab2 as (select tab.*, 
                sum(case when min_date <> 1 then debit else 0 end) over (partition by account_no) t_debit,
                sum(case when min_date <> 1 then credit else 0 end) over (partition by account_no) t_credit
           from tab)
select ACCOUNT_NO , 
       DEBIT as opening, 
       T_DEBIT as DEBIT, 
       T_CREDIT as CREDIT, 
       (DEBIT + T_DEBIT - T_CREDIT) closing
  from tab2
 where min_date = 1;

输出继电器:

| ACCOUNT_NO | OPENING | T_DEBIT | T_CREDIT | CLOSING |
|------------|---------|---------|----------|---------|
|    10-0001 |    1000 |       0 |      440 |     560 |
|    20-0001 |    3000 |    1200 |        0 |    4200 |
|    30-0001 |     300 |     500 |     1340 |    -540 |

但是,在您的插图中,最后一个帐户的结算是540,但它应该是-540

编辑: 如果对于特定日期输出id,则:

with tab as (select l.ACCOUNT_NO,
                    sum(case when gdate < '02-OCT-2013' then (debit - credit) else 0 end) opening,
                    sum(case when gdate >= '02-OCT-2013' then debit else 0 end) t_debit,
                    sum(case when gdate >= '02-OCT-2013' then credit else 0 end) t_credit
               from ledger l
              group by l.ACCOUNT_NO)
select ACCOUNT_NO , 
       opening, 
       T_DEBIT as debit, 
       T_CREDIT as credit, 
       (opening + T_DEBIT - T_CREDIT) closing
  from tab
order by 1;

答案 1 :(得分:0)

试试这个......

SELECT x.*, (x.Opening + x.Debit - x.Credit) as "CLOSING"
FROM (
    SELECT l.ACCOUNT_NO as "ACCOUNT_NO",
        (SELECT DEBIT FROM ledger l2 
         WHERE l2.ACCOUNT_NO = l.ACCOUNT_NO AND l2.gdate < '02/10/2013') as "OPENING"
        SUM(l.DEBIT) as "DEBIT", SUM(l.CREDIT) as "CREDIT" 
    FROM ledger as l
    GROUP BY l.ACCOUNT_NO
) as x