【问题标题】:ORACLE SQL Range of hoursORACLE SQL 小时范围
【发布时间】:2019-05-28 16:02:18
【问题描述】:

我有一个问题,我有一个有 3 列的表

- date - varchar2   - varchar2 -   
| date | start_hour | end_hour |  

我需要验证不重叠小时范围。
例如:

| date  | start_hour | end_hour |  
| date1 | 09:00AM    | 09:30AM  |  
| date1 | 10:30AM    | 11:30AM  |  
| date1 | 01:00PM    | 03:00PM  |  

假设 3 行的日期相同。
我需要的是,这些范围不重叠
我不能插入这样的范围
start_hour = 08:00AM 和 end_hour = 09:20AM,因为 09:00AM 和 09:30AM 之间的范围已经存在,因此,新范围与表中存在的范围冲突。 我尝试了很多查询,而不是介于两者之间,我插入的 end_hour 需要小于表中的 start_hour。 有人知道怎么做吗?

【问题讨论】:

  • 您的列的数据类型是什么? Oracle 没有time 数据类型。
  • 忘记放了,是varchar2
  • 您使用的是哪个版本的 Oracle?
  • 首先,我会告诉您以 24 小时格式而不是 AM/PM 存储这些值,以便正确排序值。
  • 嗨,APC,现在是 18.0

标签: sql oracle plsql date-range


【解决方案1】:

我假设您已将时间格式转换为hh24:mi

也许这会有所帮助:

with tab as(
select 'date1' as dat,  '09:00' as  start_hour, '09:30' as end_hour from dual union all
select 'date1' as dat,  '10:30' as  start_hour, '11:30' as end_hour from dual union all
select 'date1' as dat,  '13:00' as  start_hour, '15:00' as end_hour from dual 
)
SELECT COUNT(*)
  FROM   tab
  WHERE  start_hour <= '09:10' --:new_end_hour
  AND    end_hour   >= '07:00' --:new_start_hour
  AND    dat = 'date1'
  ;

或者您可以使用between 在值之间检查start_hourend_hourist

with tab as(
select 'date1' as dat,  '09:00' as  start_hour, '09:30' as end_hour from dual union all
select 'date1' as dat,  '10:30' as  start_hour, '11:30' as end_hour from dual union all
select 'date1' as dat,  '13:00' as  start_hour, '15:00' as end_hour from dual 
)
SELECT COUNT(*)
  FROM   tab
  WHERE  ('09:00' between start_hour and end_hour
  or    '09:10' between start_hour and end_hour
  )
  AND    dat = 'date1'
  ;

db小提琴here

【讨论】:

  • 您好,感谢您的帮助,我已经找到了解决方案,我已确认,非常感谢您的帮助!
【解决方案2】:

我已经找到了我的问题的解决方案,作为我问题中的评论的建议,当我更改时间的格式和新时间的格式时,它工作得很好。 这是将来遇到同样问题的人的代码。

DECLARE
  l_count NUMBER(1) := 0;
BEGIN

  SELECT COUNT(*)
  INTO   l_count
  FROM   table
  WHERE  start_hour <= :new_start_hour
  AND    end_hour   >= :new_end_hour
  AND    date = :date
  AND    ROWNUM     = 1;
  dbms_output.put_line(l_count);

END;
/

感谢我们的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2011-03-29
    • 2018-06-20
    相关资源
    最近更新 更多