从开始日期到结束日期的每个日期的行

Row for each date from start date to end date

我想做的是记录如下所示:

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

并将其更改为如下所示:

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

可以在 Python 中完成,但我不确定 SQL Oracle 是否可行?我很难完成这项工作。任何帮助将不胜感激。

谢谢

使用递归 subquery-factoring 子句:

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;

您的示例数据:

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

输出:

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

connect by level 对这些问题很有用。假设名为“table_DT”的第一个 CTE 是您的 table 名称,因此您可以在之后使用 select 语句。

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
;