Reputation: 13
I'd like to know how to calculate full years and number of full months between two dates and combine them into one column:
Ex: My beginning date is a column named "TransferDate" = 7/1/2017 and Today (11/14/2019) My desired output would be a column named "Age" = 2.3
2 Full Years (2017 - 2019) .3 Full Months (August, September & October)
Upvotes: 1
Views: 523
Reputation: 658
This combines the year and month components into a single column after calculating them as monthdif and yeardif.
DECLARE @start DATETIME = '07/01/2017'
DECLARE @end DATETIME = '11/14/2019'
select CAST((CAST(x.yeardif as nvarchar(20)) + '.' + CAST(x.monthdif as nvarchar(20))) as decimal(5,2)) from
(select DATEDIFF(yyyy,@start,@end) yeardif,DATEDIFF(m,@start,@end) - (12 * DATEDIFF(yyyy,@start,@end)) - 1 monthdif) x
Upvotes: 0
Reputation: 163
Take a look and see if this gives you what you are looking for.
Declare @date1 date = '11/01/2001'
Declare @date2 date = '12/01/2002'
Select @date1
,@date2
,Case
when datediff(M,@date1,@date2) < 12 then ''
when datediff(M,@date1,@date2) < 24 then 'one year'
else cast(floor(datediff(M,@date1,@date2)/12) as varchar(20)) + ' Years'
end + ' ' +
Case
when datediff(M,@date1,@date2) - floor(datediff(M,@date1,@date2)/12)*12 = 0 then ''
when datediff(M,@date1,@date2) - floor(datediff(M,@date1,@date2)/12)*12 = 1 then 'one month'
else cast(datediff(M,@date1,@date2) - floor(datediff(M,@date1,@date2)/12)*12 as varchar(20)) + ' Months'
end
Upvotes: 1