生成日期和时间的顺序

时间:2015-08-07 21:35:40

标签: oracle oracle11g oracle10g

是否可以在下面更改此查询,以便与“OPEN”相同而不是最后的“INTERVALENDTIME”。除非它是新的一天,否则它将是“开放”

例如,以下是当前版本的几行日期:

  DT            OPEN                CLOSE          NAME    INTERVAL END
8/4/2015    8/4/2015 9:00:00 AM 8/4/2015 2:00:00 PM Bob 8/4/2015 1:00:00 PM
8/4/2015    8/4/2015 9:00:00 AM 8/4/2015 2:00:00 PM Bob 8/4/2015 2:00:00 PM
8/5/2015    8/5/2015 9:00:00 AM 8/5/2015 2:00:00 PM Bob 8/5/2015 10:00:00 AM
8/5/2015    8/5/2015 9:00:00 AM 8/5/2015 2:00:00 PM Bob 8/5/2015 11:00:00 AM
8/5/2015    8/5/2015 9:00:00 AM 8/5/2015 2:00:00 PM Bob 8/5/2015 12:00:00 PM

以及结果应该是

  DT            OPEN                CLOSE          NAME    INTERVAL END
8/4/2015   8/4/2015 12:00:00 PM 8/4/2015 2:00:00 PM Bob 8/4/2015 1:00:00 PM
8/4/2015    8/4/2015 1:00:00 PM 8/4/2015 2:00:00 PM Bob 8/4/2015 2:00:00 PM
8/5/2015    8/5/2015 9:00:00 AM 8/5/2015 2:00:00 PM Bob 8/5/2015 10:00:00 AM
8/5/2015   8/5/2015 10:00:00 AM 8/5/2015 2:00:00 PM Bob 8/5/2015 11:00:00 AM
8/5/2015   8/5/2015 11:00:00 AM 8/5/2015 2:00:00 PM Bob 8/5/2015 12:00:00 PM

这是查询

with par as (
  select date '2015-08-07' enddate, 4 LookBackDays, 3600 inteval, 'Bob' Name, 
         '09:00' open, '14: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
谢谢。

1 个答案:

答案 0 :(得分:1)

我认为你想使用滞后函数和dt分区... 希望这会有所帮助。

with par as (
  select date '2015-08-07' enddate, 4 LookBackDays, 3600 inteval, 'Bob' Name, 
         '09:00' open, '14: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, 
       lag(to_date(dt||' '||tm, 'yyyy-mm-dd hh24:mi'), 1,to_date(dt||' '||open, 'yyyy-mm-dd hh24:mi'))over(partition by to_date(dt||' '||open, 'yyyy-mm-dd hh24:mi') order by tm) 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