无法在SQL Server 2008 R2中设置条件

时间:2014-09-05 11:51:34

标签: sql sql-server tsql sql-server-2008-r2

我在测试表中有以下数据集:

create table test
(
columndate date,
columntime datetime
)

insert into test values('2014-01-01','22:00:00')
insert into test values('2014-01-02','06:00:00')
insert into test values('2014-01-03','23:00:00')
insert into test values('2014-01-04','05:00:00')
insert into test values('2014-02-01','10:00:00')
insert into test values('2014-02-01','13:00:00')
insert into test values('2014-02-01','15:00:00')
insert into test values('2014-02-01','05:00:00')      

columndate       columntime
------------------------------------
2014-01-01  1900-01-01 22:00:00.000
2014-01-02  1900-01-01 06:00:00.000
2014-01-03  1900-01-01 23:00:00.000
2014-01-04  1900-01-01 05:00:00.000
2014-02-01  1900-01-01 10:00:00.000
2014-02-01  1900-01-01 13:00:00.000
2014-02-01  1900-01-01 15:00:00.000
2014-02-01  1900-01-01 05:00:00.000

现在我想在结果中仅显示夜间时间,例如:

columndate       columntime
-----------------------------------
2014-01-01  1900-01-01 22:00:00.000
2014-01-02  1900-01-01 06:00:00.000
2014-01-03  1900-01-01 23:00:00.000
2014-01-04  1900-01-01 05:00:00.000
2014-02-01  1900-01-01 05:00:00.000

我正在尝试以下脚本:

select * from test
where columndate between '2014-01-01' and  '2014-02-01'
  and cast(columntime as time) between '06:00:00' and '23:00:00'

注意:我不会得到时间05:00:00

的记录

但是当我使用以下脚本时:

select * from test
where columndate between '2014-01-01' and  '2014-02-01'
  and cast(columntime as time) between '05:00:00' and '23:00:00'    

注意:我会得到预期的结果,但我正在记录时间06:00:00,我也不想表示。

我该如何解决?

2 个答案:

答案 0 :(得分:2)

你真的很接近:而不是BETWEEN你需要使用一对>=<=,因为你需要的时间间隔:< / p>

select * from test
where columndate between '2014-01-01' and  '2014-02-01'
  and (cast(columntime as time) <= '05:00:00' OR cast(columntime as time) >= '23:00:00')

Demo.

答案 1 :(得分:0)

这是否符合您的需求?:

select * from test
where columndate between '2014-01-01' and  '2014-02-01'
  and cast(columntime as time) between '05:00:00' and '23:00:00' and columntime ! ='06:00:00'