SQL查询开始时间

时间:2014-01-14 10:01:11

标签: sql sql-server sql-server-2008 time

尝试查找一个查询以选择将在08:00到第二天08:00的特定时间开始的数据,我有单独的日期和时间字段,并且还从日期到日期选择特定条件。

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

2 个答案:

答案 0 :(得分:0)

不明白为什么datefieldtimefield未保存在datetime列中。 另外我不知道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

答案 1 :(得分: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))