Reputation: 3
I am trying to calculate tenure in years based on data in this format 2 year(s), 11 month(s), 5 day(s). Below is the logic in oracle. I am trying to implement similar solution in SQL Server. Can you please help?
In this example 2 year(s), 11 month(s), 5 day(s) is converted to 2.93 years.
round(
(regexp_substr(tenure_in_current_job,'[^ ]+')
+ REGEXP_REPLACE(tenure_in_current_job,'(.*r\(s\), )(\d+)(.*)','\2')/12
+ REGEXP_REPLACE(tenure_in_current_job,'(.*h\(s\), )(\d+)(.*)','\2')/365),
2 )
Upvotes: 0
Views: 46
Reputation: 1115
select sum(num.val * 1.0 / case when trm.val like '%year%' then 1 when trm.val like '%month%' then 12 else 365 end)
from string_split('2 year(s), 11 month(s), 5 day(s)',',')
cross apply (select ltrim("value")) trm(val)
cross apply (select cast(left(trm.val,charindex(' ',trm.val)-1) as int)) num(val)
--------------
2.930365296802
Caveat: string_split was introduced in SQL Server 2016. If you're on SQL 2012 or older, this solution won't work.
Upvotes: 2