【问题标题】:SQL Query not working with certain times in where conditionSQL Query 在 where 条件下的某些时间不起作用
【发布时间】:2018-08-24 18:37:24
【问题描述】:

我在 DB2 中创建了一个表。该表有 4 个字段 ID(Integer)、Shift(Integer)、Start_time(Time) 和 End_time(Time)。此表中的数据类似于this。当我运行这个select * from shifttimes where '6:29:59' between start_time and End_time SQL 查询时,它返回“1”作为班次号。早上 5 点到下午 1:29 之间的任何时间,它都会返回“1”作为班次号,这很好。

当我运行这个select * from shifttimes where '20:29:59' between start_time and End_time sql 查询时,它返回“2”作为班次号。在下午 1:30 到晚上 8:29:59 之间的任何时间,它都会返回“2”作为班次号,这也很好。

问题是当我运行这个select * from shifttimes where '20:30:00' between start_time and End_time sql 查询时,它什么也没返回。 从 20:30:00 到 4:59:00 的任何时间,查询都不返回任何内容。 我在 TOAD for DB2 中执行所有这些查询。

【问题讨论】:

  • 您是否尝试将字符串转换为 TIME 值?像这样:TIME ('12:00:00')
  • 我将此解释为班次 3 跨越两天午夜,但 DB2 应该如何知道这一点?如果是这种情况,您需要 datetime 代替。
  • 是的,你需要一个时间戳来完成这些跨越午夜的时间。

标签: sql time db2 toad


【解决方案1】:

你想要的逻辑是:

select *
from shifttimes
where (start_time < end_time and '20:29:59' between start_time and End_time) or
      (start_time > end_time and '20:29:59 not between end_time and start_time)

问题(您可能已经注意到)是超过午夜边界的班次。第二个条件处理。

【讨论】:

  • 感谢您的解释,戈登。发布此问题后,我发现查询不起作用,因为结束时间小于开始时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-25
  • 2013-12-31
  • 2021-11-10
  • 2020-01-16
  • 1970-01-01
  • 2016-08-11
  • 1970-01-01
相关资源
最近更新 更多