In SQL I have a criteria to subtract one month from the YYYYMM value. Kindly help me. I able to get answer with below
select 201608 - 1;
But when it is 01 month, It doesn't works.
Help me on this, without checking 01 month in if condition !
I also went through DATADD and DATEDIFF functions, but couldn't able to get results as expected
Select DateAdd(MM,-1,cast(cast(201608 as varchar(10))+'01' as date))
返回2016-07-01的日期
SQL contains date manipulation functions. Use those:
SELECT DATEDIFF(DAY, DATEADD(day, -1, @dateToCheck), GETDATE())
Alternatively you can use some math to convert int into base 12 int , substract month and return back to original encoding.
select d, m, res=(dd/12)*100 + dd%12 + 1
from (
select *, (d/100)*12 + d%100 - 1 - m as dd
from ( --sample data, m = months to substract
values
(201608, 10), (201608, 2), (201601, 1), (201601, 12)
) t(d,m)
) t
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.