0

I have this table with date range:

SID StartDate EndDate CID Time_Stamp
1001 2021-04-14 2021-04-15 1002 2021-04-14
1003 2021-04-14 2021-04-16 1004 2021-04-14

What I need is to break down the dates so it would look like this.

SID StartDate EndDate CID Time_Stamp
1001 2021-04-14 2021-04-15 1002 2021-04-14
1001 2021-04-15 2021-04-15 1002 2021-04-14
1003 2021-04-14 2021-04-16 1004 2021-04-14
1003 2021-04-15 2021-04-16 1004 2021-04-14
1003 2021-04-16 2021-04-16 1004 2021-04-14

I have the following code but it does not break down the dates and only gives the date range.

if trunc(EndDate) > trunc(StartDate) then
   lv_start_date := trunc(StartDate);
   WHILE trunc(lv_start_date) <= trunc(EndDate) LOOP
     insert into mytable values (SID, trunc(lv_start_date), trunc(EndDate), 
                                        CID,Time_Stamp);
     commit;
     lv_start_date := lv_start_date + 1;
   END LOOP;
end if;

Is there any way to improve the code to get the expected result?

1 Answer 1

1

A little bit of hierarchical query and you get what you want:

SQL> select sid,
  2         startdate + column_value - 1 as startdate,
  3         enddate,
  4         cid,
  5         time_stamp
  6  from test cross join
  7    table(cast(multiset(select level from dual
  8                        connect by level <= enddate - startdate + 1
  9                       ) as sys.odcinumberlist))
 10  order by sid, startdate;

       SID STARTDATE  ENDDATE           CID TIME_STAMP
---------- ---------- ---------- ---------- ----------
      1001 2021-04-14 2021-04-15       1002 2021-04-14
      1001 2021-04-15 2021-04-15       1002 2021-04-14
      1003 2021-04-14 2021-04-16       1004 2021-04-14
      1003 2021-04-15 2021-04-16       1004 2021-04-14
      1003 2021-04-16 2021-04-16       1004 2021-04-14

SQL>
Sign up to request clarification or add additional context in comments.

2 Comments

This worked as well. What about if I wanted to delete the result I got from the select statement? How would it look like?
One option might be this: delete from test where sid in (select sid from test cross join ... as sys.odcinumberlist)));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.