SQL 查询以在一天的两个时间之间进行选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10035769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 15:13:26  来源:igfitidea点击:

Query to Select Between Two Times of Day

sqltsqlsql-server-2005

提问by ImGreg

I am trying to build a query that will select based on a DateTimecolumn SyncDate.

我正在尝试构建一个基于DateTime列进行选择的查询SyncDate

As some background, the table I query from gets imports daily in the thousands at the exact same time everyday. I want to find the entries that did not import at the "regular" time of day.

作为一些背景,我查询的表每天在完全相同的时间每天都有数千个导入。我想找到没有在一天中的“常规”时间导入的条目。

Therefore, I want to query where the time in the DateTimecolumn is between two times: lets say 14:00-14:30 (2-230) on ANY day/month/year period.

因此,我想查询DateTime列中的时间在两次之间的位置:假设在任何日/月/年期间的 14:00-14:30 (2-230)。

SELECT * FROM MyTable
WHERE DatePart(SyncDate, ..?) BETWEEN (14:00..?) and (14:30..?)

The DatePartfunction seems to be what I need, but I don't understand how to apply it to this situation. Your help is much appreciated oh great queriers.

DatePart功能似乎是我需要的,但我不明白如何将其应用于这种情况。非常感谢您的帮助哦伟大的查询者。

EDIT: I was mistaken, I am running SQL-Server-2005 as my backend. Sorry!

编辑:我错了,我运行 SQL-Server-2005 作为我的后端。对不起!

回答by marc_s

Since you're on SQL Server 2008, you can use the new TIMEdatatype:

由于您使用的是 SQL Server 2008,您可以使用新的TIME数据类型:

SELECT * FROM MyTable
WHERE CAST(SyncDate AS TIME) BETWEEN '14:00' and '14:30'

If your backend isn't 2008 yet :-) then you'd need something like:

如果您的后端还不是 2008 年 :-) 那么您需要类似的东西:

SELECT * FROM MyTable
WHERE DATEPART(HOUR, SyncDate) = 14 AND DATEPART(MINUTE, SyncDate) BETWEEN 0 AND 30

to check for 14:00-14:30 hours.

检查 14:00-14:30 小时。

回答by larryr

How about this....

这个怎么样....

select * from MyTable where
cast(cast(datepart(HH,SyncDate) as char(2)) + cast(datepart(HH,SyncDate) as char(2)) as int) between 1400 and 1430