Reputation: 13
I want to get the records of last month based on my table [Sales], variable "SoldDate" in SQL Server.
For example, if today is 29/09/2021, I want to get the data for 01/08/2021-31/08/2021
The "SoldDate" variable is in the format 2018-04-11 00:00:00.000.
I would really appreciate your help! I have no idea how to get this to work :(
Upvotes: 0
Views: 78
Reputation: 71144
The best way to search through an indexed table is to calculate what date range you need, and filter on that. You can use DATEADD
and EOMONTH
for this. Note that since you have a time component, you cannot just use EOMONTH
SELECT *
FROM YourTable
WHERE SoldDate >= DATEADD(day, 1, EOMONTH(GETDATE(), -2))
AND SoldDate < DATEADD(day, 1, EOMONTH(GETDATE(), -1))
EOMONTH
gives you the end of a month, the second parameter denotes how many months to shift.>= AND <
, this dealls correctly with the time component.Upvotes: 1
Reputation: 50163
You can use eomonth() :
SELECT DATEADD(DAY, 1, EOMONTH(SoldDate, -2)) AS StartDate, EOMONTH(SoldDate, -1) AS EndDate
Upvotes: 1