Oracle Query用于开放和结束余额

时间:2014-01-28 13:44:54

标签: 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)

这更像是评论,因为它没有回答这个问题。您的查询简化为:

Select account_no, LAG(closing, 1 ,0) OVER (order by account_no) as opening,
       debit, credit,
       (LAG(closing,1,0) OVER (order by account_no )+ closing) as closing
from (select account_no, 0 as OPEN, SUM(debit) as debit, SUM(credit) as credit,
             sum(debit) - sum(credit) as closing
      FROM ledger
      where gdate > '20-oct-13'
      group by account_no
     ) a;

一些笔记。除非您在下一个外部查询中选择order by,否则子查询或CTE中的rownum无用。如果您希望对结果进行排序,请在外部查询中添加order by

查询本身没有意义。为什么期初余额来自之前的帐号?通常,此类术语用于特定帐户的日期,并且您已删除group by子句中的所有日期。

答案 1 :(得分:1)

您不断更改自己的要求,但根据您目前所显示的内容,这可行:

select account_no,
 max(opening) keep (dense_rank first order by gdate) as opening,
 sum(debit) as debit,
 sum(credit) as credit,
 max(closing) keep (dense_rank first order by gdate desc) as closing
from (
 select account_no, gdate, credit, debit,
 lag(balance, 1, 0) over (partition by account_no order by gdate) as opening,
 balance as closing
 from (
  select account_no, gdate, debit, credit,
  sum(debit) over (partition by account_no order by gdate) as sum_debit,
  sum(credit) over (partition by account_no order by gdate) as sum_credit,
  sum(credit) over (partition by account_no order by gdate)
   - sum(debit) over (partition by account_no order by gdate) as balance
  from ledger
 )
)
where gdate > date '2013-10-02'
group by account_no
order by account_no;

当你有不同的数据时,我之前链接的逻辑是相同的。 SQL Fiddle

我不确定为什么你的开放余额显示为积极的;当你所有的都是借记时,似乎是错的。如果这真的是你想要的,那么只需交换计算余额的方式:

...
  sum(debit) over (partition by account_no order by gdate)
   - sum(credit) over (partition by account_no order by gdate) as balance
...

SQL Fiddle