查询以生成日期时间列表

时间:2015-08-07 13:51:28

标签: oracle oracle11g oracle10g

我想构建一个名为:

的变量的查询
    EndDate --this is a date
    LookBackDays --this is an integer
    Interval -- this is an interval in SECONDS
    Name -- this is  a string
   open -this is a string and is hours and minutes  in 24HH
   close - this is string and is hours and minutes in 24HH

让我说我把我的变量设置为:

EndDate to 7/4
LookBackDays  = 3
Inteval = 300 seconds
Name = "BOB"
open = "09:00"
close = "13:00"

然后我想生成一个从Endate-LookbackDays到EndDate的日期列表,它们看起来像

这看起来像

  Date     Open      Close       Name
7/1/2015   09:00 AM    13:00 PM    Bob
7/2/2015   09:00 AM    13:00 PM    Bob
7/3/2015   09:00 AM    13:00 PM    Bob
7/4/2015   09:00 AM    13:00 PM    Bob
....
....

然后对于每个日期,我想使用Interval参数添加其他行,其中对于每一行,我将基于间隔的从打开时间到关闭时间的时间间隔分解为桶,因此间隔为300秒结果将是:

   date          oepn                close             name    IntervalEnd
 7/1/2015    7/1/2015 09:00 AM   7/1/2015 13:00 PM    Bob        09:05 AM
 7/1/2015   7/1/2015 09:00 AM   7/1/2015 13:00 PM    Bob        09:10 AM
 7/1/2015  7/1/2015 09:00 AM   7/1/2015 13:00 PM    Bob        09:15 AM
 7/1/2015  7/1/2015 09:00 AM    7/1/2015 13:00 PM    Bob        09:20 AM
 7/1/2015  7/1/2015 09:00 AM   7/1/2015 13:00 PM    Bob        09:25 AM
....
....
 7/1/2015   09:00 AM   7/1/2015 13:00 PM    Bob       7/1/2015 12:55 PM
 7/1/2015   09:00 AM   7/1/2015 13:00 PM    Bob       7/1/2015 01:00 PM
 **7/2/2015**  7/2/2015 09:00 AM   7/2/2015 13:00 PM    Bob        09:05 AM
 7/2/2015  7/2/2015 09:00 AM   7/2/2015 13:00 PM    Bob        09:10 AM
 7/2/2015  7/2/2015 09:00 AM   7/2/2015 13:00 PM    Bob        09:15 AM
 7/2/2015  7/2/2015 09:00 AM   7/2/2015 13:00 PM    Bob        09:20 AM
 7/2/2015  7/2/2015 09:00 AM   7/2/2015 13:00 PM    Bob        09:25 AM
....
....
 7/2/2015  7/2/2015 09:00 AM   7/2/2015 13:00 PM    Bob        12:55 PM
 7/2/2015  7/2/2015 09:00 AM   7/2/2015 13:00 PM    Bob        01:00 PM

......等等每一天。所以基本上我每天都要把它扩展到多个桶中

1 个答案:

答案 0 :(得分:2)

您可以交叉加入两个分层查询,例如:

with par as (
  select date '2015-07-04' enddate, 3 LookBackDays, 300 inteval, 'Bob' Name, 
         '09:00' open, '13:00' close from dual),
t1 as (
  select to_char(enddate-level+1, 'yyyy-mm-dd') dt, name, open, close from par
    connect by level <= LookBackDays + 1 ),
t2 as (
  select to_char(to_date(open, 'hh24:mi') + (level) * inteval / (24*60*60), 'hh24:mi') tm
    from par
    connect by to_date(open, 'hh24:mi') + level * inteval / (24*60*60) 
               <= to_date(close, 'hh24:mi') )
select to_date(dt, 'yyyy-mm-dd') dt, 
       to_date(dt||' '||open, 'yyyy-mm-dd hh24:mi') open, 
       to_date(dt||' '||close, 'yyyy-mm-dd hh24:mi') close, name, 
       to_date(dt||' '||tm, 'yyyy-mm-dd hh24:mi') IntervalEnd
  from t1 cross join t2 order by dt, tm

SQLFiddle demo