在from_date和to_date表列之间选择天日期

时间:2018-10-14 14:13:14

标签: sql oracle

我有以下表格数据:

ID       FROM_DATE     TO_DATE
1        01/02/2018    05/02/2018
2        06/02/2018    10/02/2018

我需要从该表中选择以下数据:

ID      Day_Date
1       01/02/2018
1       02/02/2018
1       03/02/2018
1       04/02/2018
1       05/02/2018
2       06/02/2018
2       07/02/2018
2       08/02/2018
2       09/02/2018
2       10/02/2018

因此可以在oracle数据库中获得该结果吗?!

3 个答案:

答案 0 :(得分:2)

尝试内部联接包含日期的日历表,以覆盖当前表中数据的所有内容:

WITH dates AS (
    SELECT TRUNC (SYSDATE - ROWNUM) dt
    FROM DUAL CONNECT BY ROWNUM < 366
)

SELECT
    t.ID, d.dt AS Day_Date
FROM dates d
INNER JOIN yourTable t
    ON d.dt BETWEEN t.FROM_DATE AND t.TO_DATE
ORDER BY
    d.dt;

enter image description here

Demo

答案 1 :(得分:2)

您可以将connect by level的贡献与cross join子句一起使用:

with t(ID,from_date,to_date) as
(
 select 1, date'2018-02-01', date'2018-02-05' from dual union all
 select 2, date'2018-02-06', date'2018-02-10' from dual
)
select ID, min(from_date) + level - 1 as "Day_Date"
  from dual cross join t
 connect by level <= to_date - from_date + 1  
 group by ID, from_date, level
 order by ID;

Rextester Demo

答案 2 :(得分:0)

另一个变体可能是使用以开始和结束日期为输入的流水线表函数 包声明:

create or replace package tst_pkg as 
  type xx is table of date; 
  function get_days (start_date date, end_date date) return xx pipelined; 
end tst_pkg;

包装体:

CREATE OR REPLACE
PACKAGE BODY TST_PKG AS

  function get_days (start_date date, end_date date) return xx pipelined AS
  BEGIN
    for xx in 0 .. (end_date - start_date) loop 
      pipe row (trunc(start_date + xx)); 
    end loop; 
  END get_days;

END TST_PKG;

查询将类似于下面的查询

select id, column_value from emp, table(tst_pkg.get_days(start_date, end_date)) ;