Oracle SQL 语句查找两个时间戳列之间输入时间戳的行

Oracle SQL statement to find the row with input time stamp between two timestamp columns

我在 Oracle DB

中有一个 table
|SHIFT|     START_TIME (TIMESTAMP)     |      END_TIME (TIMESTAMP)      |
|  2  |  01-AUG-15 11.00.00.000000 PM  |  02-AUG-15 08.00.00.000000 AM  |
|  4  |  01-AUG-15 07.00.00.000000 AM  |  01-AUG-15 04.00.00.000000 PM  | 
|  3  |  01-AUG-15 02.00.00.000000 AM  |  01-AUG-15 11.00.00.000000 AM  | 
|  1  |  01-AUG-15 02.00.00.000000 PM  |  01-AUG-15 11.00.00.000000 PM  | 
|  5  |  01-AUG-15 08.30.00.000000 AM  |  01-AUG-15 05.30.00.000000 PM  | 

我希望返回对应于特定时间戳的那些行。 运行 以下查询有效:

select shift, 
  cast(start_time as time), 
  cast(end_time as time)
from mytable 
where cast('12.00.00.000000 PM' as time) 
  between cast(start_time as time) and
  cast(end_time as time);

但是,相同的查询不适用于 cast('12.00.00.000000 AM' as time) 即以下查询不起作用。它 returns 0 行。我做错了什么?

select shift, 
  cast(start_time as time), 
  cast(end_time as time)
from mytable 
where cast('12.00.00.000000 AM' as time) 
  between cast(start_time as time) and
  cast(end_time as time);

我什至尝试了 start_time 和 start_time + 9 小时之间的匹配,但得到了相同的行为。

select shift,
cast(start_time as time), 
cast((start_time + numtodsinterval(9,'HOUR')) as time) 
from ata_ipd_web_shifts where cast('12.00.00.000000 PM' as time) 
BETWEEN  cast(start_time as time) AND 
cast((start_time + numtodsinterval(9,'HOUR')) as time);

那么这里的问题是什么?提取所需行的最佳方法是什么?

将要检查 INTERVAL 的一天中的时间添加到班次的开始日期和班次的结束日期。像这样:

with d as ( SELECT 2 shift, to_timestamp('01-AUG-15 11.00.00.000000 PM') start_date, to_timestamp('02-AUG-15 08.00.00.000000 AM') end_date from dual
UNION ALL SELECT 4 shift, to_timestamp('01-AUG-15 07.00.00.000000 AM'), to_timestamp('01-AUG-15 04.00.00.000000 PM') from dual
UNION ALL SELECT 3 shift, to_timestamp('01-AUG-15 02.00.00.000000 AM'), to_timestamp('01-AUG-15 11.00.00.000000 AM') from dual
UNION ALL SELECT 1 shift, to_timestamp('01-AUG-15 02.00.00.000000 PM'), to_timestamp('01-AUG-15 11.00.00.000000 PM') from dual
UNION ALL SELECT 5 shift, to_timestamp('01-AUG-15 08.30.00.000000 AM'), to_timestamp('01-AUG-15 05.30.00.000000 PM') from dual
)
select * from d
where trunc(start_date)+TO_DSINTERVAL('0 09:00:00') between start_date and end_date
OR trunc(end_date)+TO_DSINTERVAL('0 09:00:00') between start_date and end_date

请注意,时间间隔是 24 小时制,因此午夜(您在示例中使用的午夜)是 0 00:00:00。