kankon says:
sql +=
"AND MONTH(daterm) = MONTH(dateadd(dd, -3, GetDate()))"
;
To get last 3 months records you need to use BETWEEN operator and pass the from date which will be the Date before 3 Months from current Date.
sql += "AND daterm BETWEEN DATEADD(MONTH, -3, GETDATE()) AND GETDATE()";
Sample query.
DECLARE @temp AS TABLE (id INT,adv_date VARCHAR(50))
INSERT INTO @temp VALUES(1,'2022/05/05')
INSERT INTO @temp VALUES(2,'2022/04/25')
INSERT INTO @temp VALUES(3,'2022/06/03')
INSERT INTO @temp VALUES(1,'2022/01/03')
SELECT * FROM @temp
WHERE CAST(adv_date AS DATETIME) BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(MONTH,-3,GETDATE())), 0) AND DATEADD(D, -1, DATEADD(M, DATEDIFF(M, 0, GETDATE()) + 1, 0))
Output
id |
adv_date |
1 |
5/5/2022 |
2 |
4/25/2022 |
3 |
6/3/2022 |