为什么使用此 SQL 日期部分和日期参数会得到不同的结果
Why do I get different results with this SQL Date Part and date parameters
当我 运行 我的 table 上的这个 where 子句时,我得到了 2 个不同的结果,对我来说似乎我应该得到相同数量的记录。
我只使用静态日期进行测试的一个,另一个也应该检索与我尝试获取上个月结果相同的结果
我认为查询是一个会自动加载前几个月记录的报告。
WHERE
(OrderReceiptedDate >= '2015-03-01')
AND (OrderReceiptedDate <= '2015-03-31')
WHERE
(DATEPART(mm, OrderReceiptedDate) = DATEPART(mm, DATEADD(mm, - 1, GETDATE())))
AND
(DATEPART(yy, OrderReceiptedDate) = DATEPART(yy, DATEADD(mm, - 1, GETDATE())))
这是两个语句
WHERE (OrderReceiptedDate >= '2015-03-01' AND
OrderReceiptedDate <= '2015-03-31'
)
WHERE (DATEPART(month, OrderReceiptedDate) = DATEPART(month, DATEADD(month, - 1, GETDATE()))) AND
(DATEPART(year, OrderReceiptedDate) = DATEPART(year, DATEADD(month, - 1, GETDATE())))
鉴于今天是 2015 年 4 月,您期望这两个都获得 3 月的所有日期。而且,如果您的日期没有时间成分,他们会的。问题是几乎所有 3 月 31 日的日期时间都不符合第一个条件。一个例外恰好在午夜:2015-03-01 00:00:00.000.
第一个最好写成:
WHERE (OrderReceiptedDate >= '2015-03-01' AND
OrderReceiptedDate < '2015-04-01'
)
更好的写法 "get me last months date" 是这样的:
WHERE OrderReceiptedDate >= dateadd(month, -1, cast(getdate() - day(getdate()) + 1 as date)) and
OrderReceiptedDate < cast(getdate() - day(getdate()) + 1 as date)
这会在 getdate()
上进行所有计算,因此查询仍然可以利用 OrderReceiptDate
.
上的索引
当我 运行 我的 table 上的这个 where 子句时,我得到了 2 个不同的结果,对我来说似乎我应该得到相同数量的记录。
我只使用静态日期进行测试的一个,另一个也应该检索与我尝试获取上个月结果相同的结果
我认为查询是一个会自动加载前几个月记录的报告。
WHERE
(OrderReceiptedDate >= '2015-03-01')
AND (OrderReceiptedDate <= '2015-03-31')
WHERE
(DATEPART(mm, OrderReceiptedDate) = DATEPART(mm, DATEADD(mm, - 1, GETDATE())))
AND
(DATEPART(yy, OrderReceiptedDate) = DATEPART(yy, DATEADD(mm, - 1, GETDATE())))
这是两个语句
WHERE (OrderReceiptedDate >= '2015-03-01' AND
OrderReceiptedDate <= '2015-03-31'
)
WHERE (DATEPART(month, OrderReceiptedDate) = DATEPART(month, DATEADD(month, - 1, GETDATE()))) AND
(DATEPART(year, OrderReceiptedDate) = DATEPART(year, DATEADD(month, - 1, GETDATE())))
鉴于今天是 2015 年 4 月,您期望这两个都获得 3 月的所有日期。而且,如果您的日期没有时间成分,他们会的。问题是几乎所有 3 月 31 日的日期时间都不符合第一个条件。一个例外恰好在午夜:2015-03-01 00:00:00.000.
第一个最好写成:
WHERE (OrderReceiptedDate >= '2015-03-01' AND
OrderReceiptedDate < '2015-04-01'
)
更好的写法 "get me last months date" 是这样的:
WHERE OrderReceiptedDate >= dateadd(month, -1, cast(getdate() - day(getdate()) + 1 as date)) and
OrderReceiptedDate < cast(getdate() - day(getdate()) + 1 as date)
这会在 getdate()
上进行所有计算,因此查询仍然可以利用 OrderReceiptDate
.