How to Target Last Month in SQL Query

476 Views Asked by At

I'm using this code in an SQL query

WHERE [Date] >= DATEFROMPARTS(DATEPART(year,GETDATE()),DATEPART(month,GETDATE())-1,DATEPART(day,GETDATE()))
  AND [Date] <= EOMONTH(DATEFROMPARTS(DATEPART(year,GETDATE()),DATEPART(month,GETDATE())-1,DATEPART(day,GETDATE())));

The problem is come 2020 the December query will through up an error

The code I posted manages the dates between which data will be returned. It looks at the date the code is run and choose that day from last month till the end of last month. What I need is dates from the 1st till the last day of the month prior to the one this code is called in.

I will be working on this issue tomorrow, it will be interesting to see what solutions other people can come up with.

2

There are 2 best solutions below

1
Gordon Linoff On BEST ANSWER

If you want the previous month:

where date >= dateadd(month, -1, datefromparts(year(getdate(), month(getdate(), 1))) and
      date < datefromparts(year(getdate(), month(getdate(), 1))

This simply checks that it is before the first of the this month and then subtracts a month from that.

1
JamieD77 On

try this

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0),
    DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) - 1 

it will get you the previous month start and end date