过去30天的数据有效,但过去30天的数据无效吗?

时间:2019-12-19 14:36:52

标签: sql-server

获取SQL的最近30天非常简单

SELECT * FROM [myDB].[dbo].[myTable] 
WHERE [CreatedDate] >= DATEADD(day,-30,GETDATE()) 
and [CreatedDate] <= getdate() 

但是我现在正在尝试获取前30天

SELECT * FROM [myDB].[dbo].[myTable] 
WHERE [CreatedDate] >= DATEADD(day,-30,GETDATE()) 
and [CreatedDate] <= DATEADD(day,-60,GETDATE()) 

这不起作用。对我来说,我看不出过去30天如何工作,但过去30天却无法工作?我必须在这里做些愚蠢的事情,有人能说明我做错了什么吗?

3 个答案:

答案 0 :(得分:1)

您需要撤消日期范围:

SELECT * FROM [myDB].[dbo].[myTable] 
WHERE [CreatedDate] >= DATEADD(day,-60,GETDATE()) 
and [CreatedDate] <= DATEADD(day,-30,GETDATE());

答案 1 :(得分:1)

您必须更改比较

SELECT * FROM [myDB].[dbo].[myTable] 
WHERE [CreatedDate] >= DATEADD(day,-60,GETDATE()) and 
[CreatedDate] <= DATEADD(day,-30,GETDATE()) 

答案 2 :(得分:1)

以下是解决现有答案的一些替代方法:

/* this is probably my favorite of the options, very little code and would be easy to parameterize the day range */
SELECT * FROM [myDB].[dbo].[myTable] 
WHERE DATEDIFF(DAY, cast([CreatedDate] as date), cast(GETDATE() as date)) BETWEEN 30 and 60

/* casting as date will remove the need to worry about time of day */
SELECT * FROM [myDB].[dbo].[myTable] 
WHERE cast([CreatedDate] as date) between dateadd(day, -60, cast(getdate() as date))
                                      and dateadd(day, -30, cast(getdate() as date))