两个查询返回不同的数字

问题描述 投票:1回答:2

为什么这些查询会产生不同的结果

查询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 1Query 2多回来了5万名成员

sql sql-server
2个回答
2
投票

据推测,您希望第二个查询是:

select count(*) from Subscription
where Cancel >= '2016-09-01' and
      Cancel < '2016-10-01';

无论Cancel是否有时间成分,这都将返回9月的所有取消。

如果Cancel有时间组件,则您的版本将在2016-09-30错过取消。


5
投票

简单。在第二个查询中,您错过了从2016年9月30日的最后一天起的所有取消。

你应该使用:and Cancel < '2016-10-01 00:00:00.000'

© www.soinside.com 2019 - 2024. All rights reserved.