简体   繁体   中英

Row for each date from start date to end date

What I'm trying to do is take a record that looks like this:

 Start_DT    End_DT     ID
4/5/2013    4/9/2013    1

and change it to look like this:

    DT      ID
4/5/2013    1
4/6/2013    1
4/7/2013    1
4/8/2013    1
4/9/2013    1

it can be done in Python but I am not sure if it is possible with SQL Oracle? I am having difficult time making this work. Any help would be appreciated.

Thanks

Use a recursive subquery-factoring clause:

WITH ranges ( start_dt, end_dt, id ) AS (
  SELECT start_dt, end_dt, id
  FROM   table_name
UNION ALL
  SELECT start_dt + INTERVAL '1' DAY, end_dt, id
  FROM   ranges
  WHERE  start_dt + INTERVAL '1' DAY <= end_dt
)
SELECT start_dt,
       id
FROM   ranges;

Which for your sample data:

CREATE TABLE table_name ( start_dt, end_dt, id ) AS
SELECT DATE '2013-04-05', DATE '2013-04-09', 1 FROM DUAL

Outputs:

\nSTART_DT |  ID \n:------------------ |  -: \n2013-04-05 00:00:00 |  1 \n2013-04-06 00:00:00 |  1 \n2013-04-07 00:00:00 |  1 \n2013-04-08 00:00:00 |  1 \n2013-04-09 00:00:00 |  1 \n

db<>fiddle here

connect by level is useful for these problems. suppose the first CTE named " table_DT " is your table name so you can use the select statement after that.

with table_DT as (
    select 
        to_date('4/5/2013','mm/dd/yyyy') as Start_DT, 
        to_date('4/9/2013', 'mm/dd/yyyy') as End_DT, 
        1 as ID
    from dual
)
select 
    Start_DT + (level-1) as DT, 
    ID
from table_DT
connect by level <= End_DT - Start_DT +1
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM