在 Oracle 中获取前一小时的记录

问题描述 投票:0回答:1

我有一个用例,我需要获取前一小时的记录

例如:当前时间是下午 1 点 30 分,作业运行时我需要中午 12 点至下午 1 点之间的记录

我尝试过这样的事情

select CURRENT_TIMESTAMP , (CURRENT_TIMESTAMP  - interval '1' hour ) from table1;

但是这会从运行时产生记录

CURRENT_TIMESTAMP               (CURRENT_TIMESTAMP-INTERVAL'1'HOUR)
2023-08-17 14:36:39.912 +0530   2023-08-17 13:36:39.912 +0530

要求是从

得到结果
Starttime                       Endtime
2023-08-17 12:00:00.000 +0530   2023-08-17 13:00:00.000 +0530

即使我在 13-14 小时之间的任何时间运行查询

oracle time oracle11g timestamp
1个回答
0
投票

如果我理解正确的话,你必须将边界截断小时

设置日期/时间格式,一目了然;你不必这样做。

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi';

Session altered.

样本数据:

SQL> with test (id, datum) as
  2    (select 1, to_date('17.08.2023 09:25', 'dd.mm.yyyy hh24:mi') from dual union all
  3     select 2, to_date('17.08.2023 09:42', 'dd.mm.yyyy hh24:mi') from dual union all
  4     select 3, to_date('17.08.2023 10:05', 'dd.mm.yyyy hh24:mi') from dual union all
  5     select 4, to_date('17.08.2023 10:33', 'dd.mm.yyyy hh24:mi') from dual union all
  6     select 5, to_date('17.08.2023 11:20', 'dd.mm.yyyy hh24:mi') from dual
  7    )

查询:

  8  select sysdate, id, datum
  9  from test
 10  where datum >= trunc(sysdate - interval '1' hour, 'hh24')
 11    and datum <  trunc(sysdate, 'hh24');

SYSDATE                  ID DATUM
---------------- ---------- ----------------
17.08.2023 11:26          3 17.08.2023 10:05
17.08.2023 11:26          4 17.08.2023 10:33

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.