查找两个不同时间范围之间的时间

Finding a time between 2 different time ranges

我正在努力使以下查询正常工作:

select date, time, amt, tran_id
from trans
where amt > 0
      and   time between'23:00:00' and '23:59:59'
      or    time between '00:00:00' and '5:59:59'

我正在尝试查找隔夜交易,但是,'or' 语句抛出了我的其他 'and' 语句,查询返回的记录是 amt = 0.

我敢肯定这很简单,我只是在研究中没有运气。

谢谢。

   where amt > 0
   and  (
            time between'23:00:00' and '23:59:59'
    or    time between '00:00:00' and '5:59:59'
            )

您需要括号来包含仅与其他时间范围配对的 OR 范围。

注意。如果该时间列的精度比秒更精确,则使用 between 会导致不准确,我总是建议使用 >= 和 < ,例如 this

where amt > 0
   and  (
            time >= '23:00:00' 
    or    ( time >= '00:00:00' and time < '6:00:00' )'
            )

除了添加括号外:假设 time 的数据类型为 TIME 这可以简化为

select date, time, amt, tran_id
from trans
where amt > 0
      and (time >= '23:00:00' or time <= '5:59:59')

where amt > 0
      and time not between '06:00:00' and '22:59:59'

顺便说一句,时间字面量应该写成 TIME '23:00:00'