sql - 当时间范围在两天之间时如何获取特定时间范围内的记录
问题描述
我正在尝试查询特定的时间范围:
即 2021 年 1 月 1 日 - 2021 年 1 月 31 日
上述日期的所有日期的上午 5:55 - 次日凌晨 5:00 之间
解决方案
您需要从时间戳(datetime
T-SQL 的类型)中提取时间部分,并在日期过滤器之外按它们过滤。
db<>在这里摆弄
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)
)
推荐阅读
- php - 满足条件时不进入while循环
- python - 硒自动登录失败没有这样的元素:无法找到元素
- azure-devops - 无法从 Azure Devops CLI 任务运行正确的 Azure CLI 命令(错误请求)
- javascript - 在 JavaScript 中创建压缩的 JWT 有效负载
- javascript - 使用 sortType 的反应表自定义排序不适用于布尔值
- amazon-web-services - 如何在 AWS 中使用 cloudformation 设置“远程 IPv4 网络 CIDR”VPN 属性
- flutter - 多个小部件在 StreamBuilder 中使用相同的 GlobalKey
- python - 在 pytest 会话结束时收集并打印摘要
- authentication - Azure 功能:.NET Core:HTTP 触发器:Easy Auth:获取身份的对象 id
- powerbi - 使用 LYTD 时防止维度分裂