Oracle:使用SQL在日期范围之间选择日期

时间:2018-03-19 19:00:48

标签: sql oracle oracle11g

我有一个表MY_DATES (START_DATE DATE, END_DATE DATE),其数据如下:

START_DATE        END_DATE
---------------------------
18-DEC-17         07-JAN-18
27-JAN-18         06-FEB-18
08-MAR-18         18-MAR-18

我需要使用如下所示的SQL在单个列中生成表格中所有日期范围的日期:

DATES 
---------- 
18-DEC-17 
19-DEC-17 
20-DEC-17 
. 
. 
. 
06-JAN-18 
07-JAN-18 
27-JAN-18 
28-JAN-18 
29-JAN-18 
. 
. 
. 
05-FEB-18 
06-FEB-18 
08-MAR-18 
09-MAR-18 
10-MAR-18 
. 
. 
. 
18-MAR-18

我正在使用oracle 11G。感谢这方面的任何帮助。

3 个答案:

答案 0 :(得分:2)

试试这个。

WITH t (sdt, ldt) AS (SELECT MIN (START_DATE), MAX (END_DATE) FROM MY_DATES)
SELECT *
  FROM (    SELECT sdt + LEVEL - 1 AS dates
              FROM t
        CONNECT BY LEVEL <= ldt - sdt + 1) c
 WHERE EXISTS
          (SELECT 1
             FROM MY_DATES d
            WHERE c.dates BETWEEN START_DATE AND END_DATE);

Demo

答案 1 :(得分:1)

Tro要做到这一点:

with calendar as (
    select :startdate + rownum - 1 as day
    from dual
    connect by rownum < :enddate - :startdate
)
select rownum as "S.No", 
       to_date(day,'dd_mm_yyyy') as "Cal_Dt", 
       to_char(day,'day') as "DayName"
from calendar

你必须替换:startdate和:enddate,其中包含特定情况的有意义值。

答案 2 :(得分:0)

在这种情况下,将生成AVG费用并将其分布在日期范围内的月末所有日期。

CREATE table #ProductSales (ProjectID Int, ProjectName varchar(100), TotalBillableFees Money, StartDate Date, EndDate Date, DataDate Date)

  Insert into #ProductSales
  Values
  (373104,'Product Sales - Flex Creation Test',40000.00,'2019-04-01','2020-06-01','2019-08-01'),
  (375111,'Product Sales - SMART',40000.00,'2019-04-01','2019-09-01','2019-08-01')

  ;WITH Dates AS (
        SELECT ProjectiD
        ,Convert(decimal(10,2),TotalBillableFees/IIF(DATEDIFF(MONTH,StartDate,EndDate)=0,1,DATEDIFF(MONTH,StartDate,EndDate))) AS BillableFeesPerMonths,EndDate
         ,[Date] = CONVERT(DATETIME,EOMONTH(StartDate))
         FROM #ProductSales
        UNION ALL SELECT ProjectiD,BillableFeesPerMonths,EndDate,
         [Date] = DATEADD(MONTH, 1, [Date])
        FROM
         Dates
        WHERE
         Date < EOMONTH(EndDate)
) SELECT ProjectID,BillableFeesPerMonths,
 CAST([Date] as Date) Date
FROM
 Dates
 OPTION (MAXRECURSION 45)