2014-01-14 166 views
0

试图找到一个查询来选择数据,将在特定时间08:00开始,直到第二天08:00,我有单独的日期和时间字段,并从日期到日期选择特定的标准。SQL查询开始时间

select * from table 
where datefield between '2014-01-14' and '2014-01-14' 
     and timefield between '08:00' and '08:00' 
+0

您选择记录从同一天和时间。您使用的是什么RDMS?如果你使用SQL Server,你可以使用'DATEADD'。 –

+0

感谢您的合作,我们正在使用MS SQl服务器,DATEADD,据我所知是用于日期时间字段,我们需要为单独的时间和日期字段添加标准 – user3193462

+0

您是否得到了关于您的问题的答案? –

回答

0

不明白为什么datefieldtimefield不会被保存在一个datetime -column。 此外,我不知道是什么timefield是的,但如果<>作品的数据类型,这将工作:

select * from table 
where (datefield = '2014-01-14' and timefield >= '08:00') 
or (datefield = '2014-01-15' and timefield < '08:00') 

编辑:刚刚获悉你可以一起加入datetime领域的一个datetime

select * from table 
where (datefield + timefield) >= '2014-01-11 08:00' 
and (datefield + timefield) < '2014-01-13 08:00' 

Here's the source of adding them together

+0

很好,但它不起作用,如果我们选择其他日期选择*从表 其中(datefield ='2014-01-11'和timefield> = '08:00') 或(datefield ='2014-01-13 '和时间字段<'08:00') – user3193462

+0

只需编辑回答遵守。 –

+0

问题是,当比较这样的字段时(第二种解决方案),你正在杀死性能。这就是为什么我走出自己的方式,以避免解决方案 –

0
declare @from datetime = '2014-01-14 08:00' 
declare @to datetime = '2014-01-15 08:00' 
select * from table 
where datefield between cast(@from as date) and @to 
and not(datefield = cast(@from as date) and timefield < cast(@from as time)) 
and not(datefield = cast(@to as date) and timefield > cast(@to as time)) 
+0

非常感谢,它完美的工作 – user3193462

+0

@ user3193462不要忘记接受答案。如果你稍微等待一段可能的更好的答案,那也没关系。 –