2016-07-28 143 views
-1

我想在两个日期之间对SQL Server中的datetime对象进行排序。当我运行它时,它已经过滤了结果但不正确。SQL Server日期时间排序

我的代码是

where 
    cast(tbRegistrant.DateEntered as date) >= cast('2015-07-01' as date) 
    and tbRegistrant.DateEntered <= cast('2016-06-30' as date) 

回来的结果将是

2008-08-06 14:14:55.000 
2015-06-09 10:18:02.000 
2014-11-25 14:18:24.000 
2014-11-24 14:11:23.000 
2014-11-24 14:06:14.000 
2015-01-30 13:41:25.000 
2008-08-06 13:23:58.000 
2014-06-19 12:22:27.000 
2014-11-25 15:30:15.000 
2014-11-25 08:13:52.000 
2014-11-24 14:12:55.000 
2015-07-13 08:20:28.000 
+0

当你说 “之类的” 你的意思是 “过滤器”?另外,“不正确”是什么意思? –

+1

你会得到什么结果?他们以什么方式不被正确排序?请发布您的原始数据和您的排序结果。 –

+0

是筛选并返回两个指定日期之间的随机日期而不是日期 – DennisOakdale

回答

2

你的第二个条件犯规包括CAST。应该是:

where cast(tbRegistrant.DateEntered as date) >= cast('2015-07-01' as date) 
    and cast(tbRegistrant.DateEntered as date) <= cast('2016-06-30' as date); 

OR

where cast(tbRegistrant.DateEntered as date) 
     BETWEEN cast('2015-07-01' as date) and cast('2016-06-30' as date); 

但更好的是,你的约会保存为DATETEXT。现在你不能使用任何索引进行搜索。

编辑:

DEMO与OP “错误的” 数据查询带来正确的过滤器。所以也许还有别的。

enter image description here

如果你的领域是datetime你不需要CAST

SELECT * 
FROM myTable 
where [DateEntered] >= cast('2015-07-01' as date) 
    and [DateEntered] <= cast('2016-06-30' as date); 
+0

他们被保存为数据库中的日期时间..并且该语法不起作用。 – DennisOakdale

+1

“你的语法不起作用”是什么意思?你会得到一个错误,如果是,哪个? –

+0

@DennisOakdale你有什么错误? CAST适用于2008年及以后。 – scsimon

0

尝试

where cast(tbRegistrant.DateEntered as date) >= cast('20150701' as date) 
    and CAST(tbRegistrant.DateEntered) <= cast('20160630' as date)