两个查询返回不同的数字

时间:2019-03-20 14:11:44

标签: sql sql-server

为什么这些查询给出不同的结果

查询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'

这些数字相差5万。 Query 1返回的会员人数比Query 2多50k

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:2)

大概您希望第二个查询为:

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

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

如果Cancel具有时间成分,则您的版本将在2016-09-30取消取消。

相关问题