I need some help with SQL Server 2012 trying to calculate an Aging Years Field for a report.
Basically, I have two fields StartDateTime and EndDateTime and here is some sample data below:
StartDateTime EndDateTime
2006-10-10 16:08:13.523 2008-04-11 00:00:00.000
2016-05-11 13:03:48.093 2016-06-16 00:00:00.000
2016-08-01 12:44:42.990 2016-08-01 00:00:00.000
2016-05-20 17:33:27.957 2016-05-25 00:00:00.000
2006-10-19 21:41:41.350 NULL
I am currently trying to make an AgingYears field to calculate the Aging Years between both fields (as exact as possible.) And when EndDateTime is NULL, it should calculate the difference between GETDATE() and StartDateTime. When StartDateTime is greater than EndDateTime (which I don't know why I have some data like this, but I do), then it should just return back 0.
I tried doing some code based off websites I found related, but it's not helping me much and this is where I'm stuck at:
DATEDIFF(YY, StartDateTime, EndDateTime) -
CASE
WHEN DATEADD(YY,DATEDIFF(YY,StartDateTime, EndDateTime),StartDateTime)
> A.[END_DTTM]
THEN DATEDIFF(YY, StartDateTime, EndDateTime)- 1
ELSE DATEDIFF(YY, StartDateTime, EndDateTime)
END AS AgeInYears,
Any help with my code would be greatly appreciated.