TriiKyPandas
TriiKyPandas

Reputation: 53

Getting previous month of last year

I want to get the previous month data but of the following year. So if it's May 2022, I want the data for April 2021.

Here is what I currently have, but it is showing the date for 12 entire months and not just 1. Any advice would be great.

AND b.invoice_date >= DATEADD(MONTH, -12, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))                                 
AND b.invoice_date < DATEADD(MONTH, DATEDIFF(MONTH, -11, GETDATE()), 0) 

Upvotes: 0

Views: 768

Answers (1)

Roman Marusyk
Roman Marusyk

Reputation: 24569

If you can use variables

DECLARE @StartDate DATETIME, @EndDate DATETIME
SET @StartDate = DATEADD(MONTH, DATEDIFF(MONTH, 0, getdate()) - 13, 0)
SET @EndDate = DATEADD(mm, 1, @StartDate)

SELECT * FROM TABLE b
WHERE b.invoice_date >= @StartDate                         
AND b.invoice_date < @EndDate

Upvotes: 1

Related Questions