我有一个表格,其中“Created”列为日期时间。
我正在尝试查询以检查Created值的时间是否在两次之间。
第一行的创建日期时间是'2013-07-01 00:00:00.000'(午夜),我正在尝试查询时间在晚上11点到早上7点之间的项目。
select *
from MyTable
where CAST(Created as time) between '23:00:00' and '06:59:59'
但没有返回任何结果。
我是否需要将时间转换为日期时间?
答案 0 :(得分:35)
我怀疑你想在晚上11点之前检查 之前
select *
from MyTable
where CAST(Created as time) >= '23:00:00'
or CAST(Created as time) < '07:00:00'
答案 1 :(得分:7)
select *
from MyTable
where CAST(Created as time) not between '07:00' and '22:59:59 997'
答案 2 :(得分:1)
这也应该有效(即使在SQL-Server 2005中):
SELECT *
FROM dbo.MyTable
WHERE Created >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, Created - 1), 0))
AND Created < DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, Created), 0))
答案 3 :(得分:1)
我有一个非常相似的问题,想分享我的解决方案
提供此表(所有MySQL 5.6):
create table DailySchedule
(
id int auto_increment primary key,
start_time time not null,
stop_time time not null
);
选择给定时间x (hh:mm:ss)
在开始时间和停止时间之间的所有行。包括第二天。
注意:随时将NOW()
替换为x
SELECT id
FROM DailySchedule
WHERE
(start_time < stop_time AND NOW() BETWEEN start_time AND stop_time)
OR
(stop_time < start_time AND NOW() < start_time AND NOW() < stop_time)
OR
(stop_time < start_time AND NOW() > start_time)
结果
给予
id: 1, start_time: 10:00:00, stop_time: 15:00:00
id: 2, start_time: 22:00:00, stop_time: 12:00:00
NOW = 09:00:00
的选定行:2
NOW = 14:00:00
的选定行:1
NOW = 11:00:00
的选定行:1,2
NOW = 20:00:00
的选定行:无答案 4 :(得分:1)
WITH CTE as
(
SELECT CAST(ShiftStart AS DATETIME) AS ShiftStart,
CASE WHEN ShiftStart > ShiftEnd THEN CAST(ShiftEnd AS DATETIME) +1
ELSE CAST(ShiftEnd AS DATETIME) END AS ShiftEnd
FROM **TABLE_NAME**
)
SELECT * FROM CTE
WHERE
CAST('11:00:00' AS DATETIME) BETWEEN ShiftStart AND ShiftEnd -- Start of Shift
OR CAST('23:00:00' AS DATETIME) BETWEEN ShiftStart AND ShiftEnd -- End of Shift
答案 5 :(得分:0)
让我们考虑一个存储班次详细信息的表
请检查SQL查询以生成表并根据输入(时间)查找时间表
声明表格变量
declare @MyShiftTable table(MyShift int,StartTime time,EndTime time)
向表变量添加值
insert into @MyShiftTable select 1,'01:17:40.3530000','02:17:40.3530000'
insert into @MyShiftTable select 2,'09:17:40.3530000','03:17:40.3530000'
insert into @MyShiftTable select 3,'10:17:40.3530000','18:17:40.3530000'
使用另一个名为“ Flag”的字段创建另一个表变量
declare @Temp table(MyShift int,StartTime time,EndTime time,Flag int)
通过交换开始时间和结束时间向临时表添加值
插入@Temp选择MyShift,以(StartTime> EndTime)然后EndTime为例,否则StartTime结束,以(StartTime> EndTime)然后StartTime为例,否则EndTime结束,以(StartTime> EndTime)然后1否则为0,否则从@结束MyShiftTable
创建输入变量以查找Shift
declare @time time=convert(time,'10:12:40.3530000')
查询以查找与提供的时间相对应的班次
从@Temp中选择myShift,其中<br/>(@Time位于StartTime和EndTime之间, 标志= 0)或(@time不在StartTime和EndTime之间,并且Flag = 1)
答案 6 :(得分:0)
select * from dbMaster oMaster where ((CAST(GETDATE() as time)) between (CAST(oMaster.DateFrom as time)) and
(CAST(oMaster.DateTo as time)))
请检查
答案 7 :(得分:-1)
应该是AND而不是OR
select *
from MyTable
where CAST(Created as time) >= '23:00:00'
AND CAST(Created as time) < '07:00:00'