I've enjoyed myself with this one :
there are two ways to do this
1: keep left joining for as much as there could be consecutive rows
2: use recursive sql
But really if you have this kind of functionality , you might want to take a look at the new DB2 v10 feature :
Temporal data:
http://eb140.elearn.ihost.com/InfoMgmt/ ... 120207.pdf--drop table testtab;
create table testtab
(Cnr integer,
Dstrt date,
Dend date,
mngr char(2))
;
insert into testtab values (1,'2000-01-01','2002-03-13', 'M1');
insert into testtab values (2,'2002-03-14','2005-03-13', 'M1');
insert into testtab values (2,'2005-03-14','2006-02-28', 'M1');
insert into testtab values (3,'2006-03-01','2006-03-01', 'M2');
insert into testtab values (3,'2006-03-02','2006-03-02', 'M2');
insert into testtab values (3,'2006-03-03','2006-03-03', 'M2');
insert into testtab values (3,'2006-03-04','2006-03-04', 'M2');
insert into testtab values (3,'2006-03-05','2006-03-10', 'M2');
insert into testtab values (4,'2006-03-11','9999-12-31', 'M1');
select * from testtab order by Dstrt;
--Too many left joins --
select min(dstrt) as dstrt ,dend, mngr, qualitycheck from
(Select a.cnr, a.dstrt ,coalesce(d.dend,c.dend,b.dend,a.dend) as Dend, a.mngr
,case when d.dend is not null then 'Need more Left joins' else 'OK' end as qualitycheck
from testtab A
left join testtab B
on a.mngr = b.mngr
and A.Dstrt < B.Dstrt
and b.dstrt = a.dend + 1 day
left join testtab C
on a.mngr = c.mngr
and b.Dstrt < c.Dstrt
and c.dstrt = b.dend + 1 day
left join testtab D
on c.mngr = d.mngr
and c.Dstrt < d.Dstrt
and d.dstrt = c.dend + 1 day
) X
group by dend,mngr,qualitycheck
order by dstrt
;
-- Recursive method --
with cte( dstrt,dend, mngr) as (
select dstrt,dend, mngr from testtab A
where not exists (select 1 from testtab B where b.mngr=a.mngr and b.Dend = a.dstrt - 1 day)
union all
select A.dstrt,B.dend, a.mngr from cte A , testtab B
where b.mngr=a.mngr
and b.dend < '9999-12-31'
and b.Dstrt = case when a.dend = '9999-12-31' then '9999-12-31' else a.dend + 1 day end
)
select dstrt,max(dend),mngr from cte
group by dstrt,mngr
order by dstrt
drop table testtab;
I can explain it to you, but i can not understand it for you.