我的查询中的日期处理有什么区别?

时间:2015-10-02 07:20:17

标签: sql-server

我需要上个月的记录数量。到目前为止,我曾经使用过这种方法:

select 
 count(ID)
from 
 table
where
 col1 = 'somerule'
and 
 DateTimeOfInsert >= '20150901' 
and 
 DateTimeOfInsert <= '20150930'

现在我即将完成此任务,因此我必须自动提取上个月的开始和结束日期。所以这就是:

select 
 count(ID)
from 
 table
where
 col1 = 'somerule'
and 
 DATEPART(m, DateTimeOfInsert) = DATEPART(m, DATEADD(m, -1, getdate()))
and 
 DATEPART(yyyy, DateTimeOfInsert) = DATEPART(yyyy, DATEADD(m, -1, getdate()))

我唯一的问题是,此时第一个查询返回1073,第二个查询返回1124。所以问题很明显:它们之间有什么区别?两者都应该包括开始和结束日期。我无法发现它。

2 个答案:

答案 0 :(得分:2)

区别在于time的{​​{1}}分量。

这:

datetime

不会选择DateTimeOfInsert >= '20150901' and DateTimeOfInsert <= '20150930' 之类的日期。

但是这个:

20150930 15:30

将选择它,因为您只检查月份和年份。这就是第二个选择返回更多行的原因。

如果您只是更改第一个语句以便它将考虑月份最后一天的时间组件,则两个查询都将返回相同的内容:

DATEPART(m, DateTimeOfInsert) = DATEPART(m, DATEADD(m, -1, getdate()))

答案 1 :(得分:2)

这个条件:

DateTimeOfInsert >= '20150901' and  DateTimeOfInsert <= '20150930'

检索2015-09-01 00:00:00.0002015-09-30 00:00:00.000之间的记录。

如果DateTimeOfInsertDATETIME,那么这将从您的其他条件返回不同的结果。

此类查询的最佳方法是不使用BETWEEN而是使用 >= and <。在您的情况下,您希望获取上个月的记录,因此您希望使用>= start of last month< start of this month

DateTimeOfInsert >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0)    -- Beginning of previous month
AND DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)  -- Beginning of this month

上述条件也会使您的查询变得可搜索。

对于某些常见日期例程,请参阅此article.