Get every hour for a time range(获取一个时间范围内的每小时)
问题描述
所以我想要生成特定时间范围内的所有时间.
So what I am trying to is generate all the hours that are inside a specific time range.
所以考虑到上午 11 点到下午 2:00 的范围,我会得到:
So given the range 11 AM to 2:00 PM, I would get:
11:00 AM
12:00 PM
1:00 PM
2:00 PM
我试图避免存储商店可能开放的每个特定时间,只存储范围(我需要将时间与其他时间进行比较)
I am trying to avoid having to store every specific hour a store might be open and just store the range (I need to compare the hours against other times)
谢谢
推荐答案
如果你有一个 数字表(如果没有,请点击链接创建)...
If you have a numbers table (click the link to create one if you don't)...
create table test(
startTime time
, endTime time
)
insert into test
select '11:00', '14:00'
select
dateadd(hh, n.n, t.startTime) as times
from test t
inner join Numbers n
-- assuming your numbers start at 1 rather than 0
on n.n-1 <= datediff(hh, t.startTime, t.endTime)
如果这是专门的,您可以创建一个只有 24 个值的小时表.
If this is specialized, you can create an hours table with just 24 values.
create table HoursInADay(
[hours] time not null
, constraint PK_HoursInADay primary key ([hours])
)
-- insert
insert into HoursInADay select '1:00'
insert into HoursInADay select '2:00'
insert into HoursInADay select '3:00'
insert into HoursInADay select '4:00'
insert into HoursInADay select '5:00'
insert into HoursInADay select '6:00'
insert into HoursInADay select '7:00'
...
select
h.[hours]
from test t
inner join HoursInADay h
on h.[hours] between t.startTime and t.endTime
这篇关于获取一个时间范围内的每小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取一个时间范围内的每小时
基础教程推荐
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
