Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Self join with previous period record

User_GAEW1Dec 16 2018 — edited Dec 17 2018

Hello,

I need a quick help to write an SQL (Oracle query):- 

Here is the base table data:-

with t as (

select '2018-01' as period, 100 as expenses, 13 as charge_reversal, 5 as payout, 22 as payment_reversal from dual union all

select '2018-12', 115, 12, 13, 17 from dual union all

select '2018-02', 110, 15, 15, 6 from dual union all

select '2018-03', 70, 17, 7, 10 from dual union all

select '2019-02', 100, 17, 18, 27 from dual union all

select '2018-07', 130, 25, 20, 11 from dual union all

select '2018-11', 120, 16, 25, 30 from dual union all

select '2019-06', 150, 40, 25, 30 from dual

)

select * from t

order by period;

Output should be:-

       

PERIODBeginning BalanceEXPENSESCHARGE_REVERSALPAYOUTPAYMENT_REVERSALEnding Balance
2018-01010013522104
2018-0210411015156190
2018-031907017710246
2018-07246130252011342
2018-11342120162530451
2018-12451115121317558
2019-02558100171827650
2019-06650150402530765

Ending balance = Beginning_Balance + Expenses - charge_reversal - payout + payment_reversal

Beginning_Balance = Ending balance of previous period.

** For 1st record, Beginning_Balance will be zero.

I was able to perform self join as :-

where t1.ROW_NUMBER - 1 = t2.ROW_NUMBER(+)

however, I couldn't manage to write complete query to have beginning and end balance. I am using oracle 10g edition.

Any help will be much appreciated.

Regards,

Ritesh

Comments
Post Details
Added on Dec 16 2018
9 comments
945 views