1

So what I am trying to do is when I run the query, I want to return all records that were in the month two months from the current month. For example, lets say the current month is November, when the query runs, I want returned all records from September and only September. If I run the query in lets say October, I want all records from August and only August. I am trying to do this in MS SQL. Thanks for any advice.

4

4 Answers 4

0

In SQL Server, you can use:

where datecol >= dateadd(month, -3, datefromparts(year(getdate()), month(getdate()), 1)) and
      datecol < dateadd(month, -2, datefromparts(year(getdate()), month(getdate()), 1))

This is index- and optimizer- friendly. If you don't care about performance, you can use datediff():

where datediff(month, datecol, getdate()) = 2 
0

This can be done in a nice 1 liner.

WHERE NOW() BETWEEN Date1 AND Date2;

0
0

You can have the month part in a variable and then it can be used in the Where clause to filter the month part of the date value is equal to the varoable value.

Query

Declare @month as int;
Set @month=datepart(month, getdate()) - 2;

Select * from yourTableName
Where month(dateCol) = @month;
0

The function GETDATE() can be used to retrieve the current month.

The function DATEADD(datepart,number,date) can be used to perform operations on dates. For more info look at the official docs

Thus, to retrieve the records from two months before (-2) the current month you can use the following:

DATEADD(month, -2, GETDATE())

In conclusion an example query to select all records that were in the month two months from the current month:

SELECT * FROM table 
   WHERE MONTH(month_column) = DATEADD(month, -2, GETDATE())

sources:

1
  • Pls add little explanation to the answer. Nov 19, 2020 at 15:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.