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!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

How to use CONNECT BY LEVEL to get this result?

672680Apr 10 2011 — edited Apr 10 2011
Hi all,

my DB version is 10gR2.

here is the table and the data:
create table t (from_dt date, to_dt date, eno varchar2(2), deptno varchar2(10));

insert into T values (TO_DATE('2010-01-01','yyyy-mm-dd'),TO_DATE('2010-04-30','yyyy-mm-dd'),'A','DEPTA');
insert into T valueS (TO_DATE('2010-05-01','yyyy-mm-dd'),TO_DATE('2010-12-31','yyyy-mm-dd'),'A','DEPTB');
insert into T values (TO_DATE('2010-01-01','yyyy-mm-dd'),TO_DATE('2010-06-30','yyyy-mm-dd'),'B','DEPTA');
insert into T valueS (TO_DATE('2010-07-01','yyyy-mm-dd'),TO_DATE('2010-12-31','yyyy-mm-dd'),'B','DEPTB');

from_dt       to_dt           ENO   DEPTNO
------------------------------------------------
2010-01-01 2010-04-30  A     DEPTA
2010-05-01 2010-12-31  A     DEPTB
2010-01-01 2010-06-30  B     DEPTA
2010-07-01 2010-12-31  B     DEPTB
Here is the result I want:
MONTH    ENO   DEPTNO
-----------------------------
2010-01    A      DEPTA
2010-02    A      DEPTA
2010-03    A      DEPTA
2010-04    A      DEPTA
2010-05    A      DEPTB
...............
Here is what I came up with:
select distinct ADD_MONTHS(TRUNC(FROM_DT,'MON'),level-1) as MONTHS, 
       ENO, 
       DEPTNO
from (
    select FROM_DT, TO_DT, ENO, DEPTNO, ROUND(MONTHS_BETWEEN(TO_DT, FROM_DT)) as BET from T
) connect by level<=BET
order by eno, deptno,months ;
the problem with this is that, many duplicate rows are generated if I remove DISTINCT from the sql.
and I don`t know how that happens? How CONNECT BY LEVEL, returns me so many duplicate rows?

Anyone have any idea about this?
And is there any other way to do this as well?

Thanks

Comments

322340
Well, I replacing the driver libraries with some older 9iRelease 1 drivers I have, and this problem has gone away. I still don't know what might have caused it - but I would like to be able to update them at some time.
1 - 1
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on May 8 2011
Added on Apr 10 2011
10 comments
79,873 views