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!

Lag function to subtract to total from two different rows based on a value.

SeshuGiriMar 31 2015 — edited Mar 31 2015

I have a table in which I got data for accounts for each day. Most of the times on a given day there will be two rows one with code 9 and other with code 0.

I want to get total  data subtract col2 value (9) - col2 value (0). To explain further here is sample data.

I want to get the data by COL1 (Account) and by COLDATE. Right now it is grouping all accounts and not considering the date.

create table SAMPLETABLE 

  COL1   NUMBER(10) not null, 

  COLDATE       DATE not null, 

  COL2        NUMBER(15, 9) not null, 

  COLCODE NUMBER(1) 

)  ;

insert into SAMPLETABLE (COL1, COLDATE, COL2, COLCODE)

values ('9889898989', to_date('01-01-2014', 'dd-mm-yyyy'), 68.6370000000, 0);

insert into SAMPLETABLE (COL1, COLDATE, COL2, COLCODE)

values ('9889898989', to_date('02-01-2014', 'dd-mm-yyyy'), 53.4620000000, 0);

insert into SAMPLETABLE (COL1, COLDATE, COL2, COLCODE)

values ('9889898989', to_date('01-01-2014', 'dd-mm-yyyy'), 80.5020000000, 9);

insert into SAMPLETABLE (COL1, COLDATE, COL2, COLCODE)

values ('9889898989', to_date('02-01-2014', 'dd-mm-yyyy'), 110.5940000000, 9);

insert into SAMPLETABLE (COL1, COLDATE, COL2, COLCODE)

values ('10101010', to_date('01-01-2014', 'dd-mm-yyyy'), 999, 9);

Present

     

TOTALCOL1COLDATECOL2COLCODE
98898989891/1/201480.5020000009
-30.09298898989891/2/2014###########9
-888.406101010101/1/2014###########9
930.36398898989891/1/201468.6370000000
15.17598898989891/2/201453.4620000000

Expected

    

TOTALCOL1COLDATECOL2
999.000000000101010101/1/2014999.000000000
11.86500000098898989891/1/201480.502000000
57.13298898989891/2/2014110.594000000

select

(lag(c.COL2) over (order by c.COLCODE desc) - c.COL2) as total,

c.COL1

,

c.COLDATE,

c.COL2,

c.COLCODE

from SAMPLETABLE c

  where c.COLDATE BETWEEN '01-JAN-2014' AND '02-JAN-2014'

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 28 2015
Added on Mar 31 2015
1 comment
841 views