Skip to content
Advertisement

Getting previous month data not working in sql server

I am trying to get the previous month data according to the datetime in the column dynamically for example I have data like this

enter image description here

Now I want the records previous than Opendt. The problem is that I am getting the record after Opendt but I am getting empty when I am getting the record before 1 month or 2 month of Opendt

this is the query i am writing

select * from dbo.mytable where Valdate between OpenDt and dateadd(Month,-1,OpenDt)

the problem is that here -1 and -2 returning empty but when i am adding positive values 1 , 2 and 3 I am getting the records after the OpenDt but not the before Dt Records.

I need the previous one or two month records before OpenDt

Advertisement

Answer

You need to reverse the BETWEEN. The lower value must always be first.

SELECT * 
FROM dbo.mytable
WHERE Valdate BETWEEN dateadd(Month,-1,OpenDt) AND OpenDt
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement