Row for each date from start date to end date

余生长醉 提交于 2021-02-17 05:18:25

问题


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


回答1:


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
;



回答2:


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:

START_DT            | ID
:------------------ | -:
2013-04-05 00:00:00 |  1
2013-04-06 00:00:00 |  1
2013-04-07 00:00:00 |  1
2013-04-08 00:00:00 |  1
2013-04-09 00:00:00 |  1

db<>fiddle here



来源:https://stackoverflow.com/questions/64353144/row-for-each-date-from-start-date-to-end-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!