This is my query
select *
from RDR1 A
where Year(A.shipdate) = '2021'
and (
Month(A.shipdate) = Month(CURRENT_TIMESTAMP) - 1
or Month(A.shipdate) = Month(CURRENT_TIMESTAMP) + 1
or Month(A.shipdate) = Month(CURRENT_TIMESTAMP)
)
The above query works fine when they choose the year 2020, But when they choose 2021 it doesn't work. The above query should filter based on the current month. For eg: December 2020 (Current Month), Jan 2021 (next month), November (Previous Month).
How should I modify my query?
If you want the last month, this month, or next month, I would suggest:
where a.shipdate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1)) and
a.shipdate < dateadd(month, 2, datefromparts(year(getdate()), month(getdate()), 1))
This is index-friendly. If that is not a concern, you can use:
where datediff(month, s.shipdate, getdate()) between -1 and 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.