We need to filter the last 4 months (according to your comments) from the current system month.
We used the DATEADD (MONTH, -4, CONVERT (date, GETDATE ()) function to subtract 4 months from our current date and use CONVERT (date, GETDATE () ) to ignore the time.
Note: If you want to consider the time, change the CONVERT (date, GETDATE ()) to GETDATE () . If you need to change the number of months for the last 5, 6, 7 ... months, change the parameter -4 to the number of days (negatively, since we are subtracting the months) > -5, -6, -7 .
We used the DATEADD (MONTH, -1, CONVERT (DATE, GETDATE ()) function to ignore the current month.
SELECT *
FROM VIEW_INCD
WHERE DH_CRIA_INCD BETWEEN DATEADD(MONTH, -4, CONVERT(date, GETDATE())) AND DATEADD(MONTH, -1, CONVERT(DATE, GETDATE()))
ORDER BY DH_CRIA_INCD DESC
To run a query for just 1 month, you said in the comments, try the following command:
SELECT *
FROM VIEW_INCD
WHERE DH_CRIA_INCD BETWEEN DATEADD(mm, DATEDIFF(m, 0, GETDATE()) - 1, 0)
AND DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), 0))
ORDER BY DH_CRIA_INCD DESC
The first part of BETWEEN is passing the first day of the previous month (because of -1).
Note: If you want to change the month add -1, -2, -3 after the DATEADD function, but -1 refers to 1 previous month, -2 refers to 2 months previous, and so on.
Example: Since GETDATE () will return on 08/08/2018, the function below will return 01/07/2018.
DATEADD(mm, DATEDIFF(m, 0, GETDATE()) - 1, 0)
The second part of BETWEEN is passing the last day of the previous month.
Note: If you want to change the month add -1, -2, -3 after the DATEADD function, but -1 refers to 2 previous months, -2 refers to 3 months previous, and so on.
Example: Whereas GETDATE () will return on 08/08/2018, the function below will return 06/30/2018.
DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) - 1, 0))