为什么这些查询会产生不同的结果
查询1
SELECT DATEPART(YEAR, Cancel) [Year],
DATEPART(Month, Cancel) [Month], COUNT(1) [Count]
FROM Subscription
where DATEPART(YEAR, Cancel) = 2016
GROUP BY DATEPART(year, Cancel),DATEPART(Month, Cancel)
此查询可让我在2016年的每个月取消订阅。
查询2
这让我在2016年第9个月取消预订。
select count(*) from Subscription
where Cancel >= '2016-09-01 00:00:00.000'
and Cancel <= '2016-09-30 00:00:00.000'
这些数字有50k的差异。 Query 1
比Query 2
多回来了5万名成员
据推测,您希望第二个查询是:
select count(*) from Subscription
where Cancel >= '2016-09-01' and
Cancel < '2016-10-01';
无论Cancel
是否有时间成分,这都将返回9月的所有取消。
如果Cancel
有时间组件,则您的版本将在2016-09-30错过取消。
简单。在第二个查询中,您错过了从2016年9月30日的最后一天起的所有取消。
你应该使用:and Cancel < '2016-10-01 00:00:00.000'