【问题标题】:How to get records in specific time range when the time range is between two days当时间范围在两天之间时如何获取特定时间范围内的记录
【发布时间】:2021-02-10 06:55:33
【问题描述】:

我正在尝试查询特定的时间范围:

  • 即2021 年 1 月 1 日 - 2021 年 1 月 31 日

  • 上述日期的所有日期的上午 5:55 - 次日凌晨 5:00 之间

【问题讨论】:

  • 请显示示例数据(作为 DDL+DML)、预期结果(作为格式化文本)和您的尝试。
  • 您是否需要为日期范围内的所有日期提取此时间范围?
  • @astentx:是的。

标签: sql sql-server datetime sql-date-functions


【解决方案1】:

您需要从时间戳(T-SQL 的datetime 类型)中提取时间部分,并根据日期过滤器进行过滤。

db小提琴here

declare
  @dt_from datetime
  , @dt_to datetime
  , @tm_from time
  , @tm_to time
  , @dt datetime
;
  
select
  @dt = convert(datetime, '2021-02-10 11:48:36', 120)
  , @dt_from = convert(date, '2021-02-01', 23)
  , @dt_to = convert(date, '2021-02-28', 23)
  , @tm_from = convert(time, '05:55:00', 120)
  , @tm_to = convert(time, '05:00:00', 120)
;

with a as (
  select @dt as dt union all
  select dateadd(hour, 20, @dt) union all
  select dateadd(hour, -15, @dt) union all
  select dateadd(hour, -6, @dt) union all
  select dateadd(day, -30, @dt) union all
  select convert(datetime, '2021-02-01 00:01:02', 120) union all
  select convert(datetime, '2021-02-28 20:01:02', 120)
)
select *
from dt
/*Restrict dates*/
where dt >= @dt_from
  and dt < dateadd(day, 1, @dt_to)
  and (
    /*Exclude time intervals between 05:00 and 05:55*/
    cast(dt as time) <= @tm_to
    or cast(dt as time) >= @tm_from
  )

或者,如果您只需要整个时间范围都属于您的日期的情况(例如,排除开始日期的 00:00 到 05:00 和结束日期的 05:55 到 23:59:59 的时间):

select *
from dt
where dt between @dt_from and @dt_to
  and (
    /*Exclude time intervals between 05:00 and 05:55*/
    cast(dt as time) <= @tm_to
    or cast(dt as time) >= @tm_from
  )
  /*Exclude time intervals at boundary dates*/
  and not(
    (cast(dt as date) = @dt_from and cast(dt as time) <= @tm_to)
    or (cast(dt as date) = @dt_to and cast(dt as time) >= @tm_from)
  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2018-04-15
    • 1970-01-01
    • 2013-09-12
    相关资源
    最近更新 更多