Oracle查询以获取两个时间戳之间的每分钟

时间:2015-11-09 06:08:25

标签: sql oracle date-arithmetic

我需要一个oracle查询,它返回给定两个时间戳之间的每一分钟。我提到了this Stack Overflow问题。 我们可以改进相同的查询吗?

3 个答案:

答案 0 :(得分:1)

如果您希望sysdate的所有分钟数到15 NOV:

,您可以这样创建
SELECT to_char(TRUNC(sysdate) + numtodsinterval(level - 1, 'minute'),
               'dd.mm.yyyy hh24:mi') min
  FROM dual
CONNECT BY LEVEL <=
           (trunc((TO_DATE('16-NOV-2015','dd-mon-yyyy')) - sysdate) * 24 * 60);

答案 1 :(得分:1)

要使用Row Generator技术获取两个日期时间元素之间的所有分钟数,您需要将日期之间的差异转换为分钟数。其余在 CONNECT BY 子句中保持不变。

例如,要获取11/09/2015 11:00:0011/09/2015 11:15:00之间的所有分钟数:

SQL> WITH DATA AS
  2    (SELECT to_date('11/09/2015 11:00:00', 'DD/MM/YYYY HH24:MI:SS') date_start,
  3      to_date('11/09/2015 11:15:00', 'DD/MM/YYYY HH24:MI:SS') date_end
  4    FROM dual
  5    )
  6  SELECT TO_CHAR(date_start+(LEVEL -1)/(24*60), 'DD/MM/YYYY HH24:MI:SS') the_date
  7  FROM DATA
  8    CONNECT BY level <= (date_end - date_start)*(24*60) +1
  9  /

THE_DATE
-------------------
11/09/2015 11:00:00
11/09/2015 11:01:00
11/09/2015 11:02:00
11/09/2015 11:03:00
11/09/2015 11:04:00
11/09/2015 11:05:00
11/09/2015 11:06:00
11/09/2015 11:07:00
11/09/2015 11:08:00
11/09/2015 11:09:00
11/09/2015 11:10:00
11/09/2015 11:11:00
11/09/2015 11:12:00
11/09/2015 11:13:00
11/09/2015 11:14:00
11/09/2015 11:15:00

16 rows selected.

以上,CONNECT BY level <= (date_end - date_start)*(24*60) +1表示我们生成的行数与(date_end - date_start)*(24*60) +1一样多。您获得16行,因为它包含分钟的开始 结束窗口。

答案 2 :(得分:1)

你也可以使用下面的代码而不是systimestamp和systimestamp + 1

 select (systimestamp)+level/(24*60) as Rang_values
    from
    dual
    connect by level
    <=
    (
    select extract( minute from diff)+
    extract(day from diff)*24*60 +
    extract(hour from diff)*60 as diff
     from
    ( 
    select systimestamp+1-systimestamp diff from dual
    )
    )