Home > Mobile >  How can I subtract two integers datewise in SQL Server?
How can I subtract two integers datewise in SQL Server?

Time:07-05

I have a table which has years as int, say 202101. I want to get the difference in months with 202205.

For example 202205 - 202101 = 16 (months).

Do you know how can I do that?

CodePudding user response:

Just to expand on Larnu's comment.

select datediff(month
      ,try_convert(date,concat(202101,'01'))
      ,try_convert(date,concat(202205,'01'))
      )

Results

16

CodePudding user response:

If you do integer division by 100 you get the year component with the remainder as the month component so another method is

DECLARE @Date1 INT =202205, @Date2 INT = 202101

SELECT  (12 * (@Date1/100 - @Date2/100))   (@Date1 % 100 - @Date2 % 100)
  • Related