在where子句的getdate()和DATEADD(m,-1,getdate())之间

问题描述 投票:0回答:4

为什么"where SomeDate between getdate() and DATEADD(m, -1, getdate()))" -不工作? (我试着计算一些上个月的价值)

sql
4个回答
0
投票

你应该用其他方式

where  SomeDate between   DATEADD(m, -1, getdate()) and getdate() 

1
投票

因为当你使用between时,较低的值需要先行。所以你要:

where SomeDate between DATEADD(month, -1, getdate()) and getdate()

0
投票

你需要像这样使用它:

WHERE SomeDate BETWEEN DATEADD(m, -1, GETDATE() and GETDATE() 

首先是较小的值,在这种情况下是DATEADD


0
投票

这里有一些例子

DECLARE @ServerDate DATETIME = GETDATE()

我添加Distinct以避免冗余数据字段

SELECT DISTINCT * FROM FooTable
WHERE SomeDate BETWEEN DATEADD(DD, 0, DATEDIFF(DD, 0, @ServerDate)) AND DATEADD(DD, 1, @ServerDate)

DATEADD(DD,0,DATEDIFF(DD,0,@ ServerDate))相当于YYYY-mm-dd 00:00:00.000

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