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

Oracle query to fetch every minute between two timestamps

我需要一个 oracle 查询,在给定的两个时间戳之间每分钟 returns。我提到了 this 堆栈溢出问题。 我们可以改进同一个查询吗?

如果您想要从 sysdate 到 11 月 15 日的所有分钟,您可以这样创建:

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);

要使用 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 行,因为它包括分钟的 start and end window。

您也可以在下面使用并给出您的值,而不是 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
    )
    )