create table accountbalance
(
custid varchar2(5) not null,
adate date not null,
balance number not null,
constraint pk_accountbalance primary key(custid, balance)
);
I have inserted the values in the first column for customer id (C1) and the values in the second column for customer id (C2).
The query:
with
a as
(
select custid selid, adate seldate, balance selbal
from accountbalance
),
b as
(
select selid testid, seldate testdate, nvl(max(adate), to_date('01-jan-1900')) prevnormaldate
from a, accountbalance
where custid = selid
and adate < seldate
and balance > -1000
group by selid, seldate
),
c as
(
select selid, seldate, selbal, prevnormaldate
from a, b
where selid = testid
and seldate = testdate
)
select selid custid, seldate trandate, min(selbal) balance, sum(case when selbal > -1000 then 0 else 1 end) odcount
from c, accountbalance
where selid = custid
and adate between prevnormaldate + 1 and seldate
group by selid, seldate
order by 1, 2
;