【问题标题】:Selecting information from a specific range of days and hours using one SQL query使用一个 SQL 查询从特定日期和时间范围内选择信息
【发布时间】:2020-04-22 11:17:06
【问题描述】:

我想过滤从 4 月 1 日到 4 月 22 日的日期范围,但仅限于晚上 8:00 到早上 6:00 之间 - 应排除不在此范围内的其余时间。你对如何做到这一点有任何想法吗?到目前为止我唯一做的是日期范围,但我不知道接下来如何处理它:

select * from cdm_service_request_logs
where inserted_at  >= '20/04/01 20:00:00%'
and inserted_at < '20/04/22 06:00:00%'
ORDER BY ID DESC;

【问题讨论】:

  • (1) 标记您正在使用的数据库。 (2) 我不明白时间过滤器。是每天还是最后几天?
  • (1) 我正在使用 Oracle SQL (2) 这是 4 月 1 日至 22 日 20:00 至 06:00 的天数范围

标签: sql date oracle-sqldeveloper


【解决方案1】:

我想你想要这样的东西:

select srl.*
from cdm_service_request_logs srl
where inserted_at >= date '2020-04-01' and
      inserted_at < date '2020-04-022' and
      extract(hour from inserted_at) not between 6 and 19;

在Oracle中,时间比较经常使用字符串:

where inserted_at >= date '2020-04-01' and
      inserted_at < date '2020-04-022' and
      (to_char(inserted_at, 'HH24:MI') >= '20:00' or
       to_char(inserted_at, 'HH24:MI') < '06:00'
      )

请注意,日期比较使用日期常量值。这是对的。 % 对日期无效,因此您的比较是字符串。我只能推测您将like 模式与日期常量混淆了。如果是这样,那只是被误导了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 2021-11-15
    相关资源
    最近更新 更多