I receive reports in which the data is ETL
to the DB automatically. I extract and transform some of that data to load it somewhere else. One thing I need to do is a DATEDIFF
but the year needs to be exact (i.e., 4.6 years instead of rounding up to five years.
The following is my script:
select *, DATEDIFF (yy, Begin_date, GETDATE()) AS 'Age in Years'
from Report_Stage;
The 'Age_In_Years'
column is being rounded. How do I get the exact date in years?
Have you tried getting the difference in months instead and then calculating the years that way? For example 30 months / 12 would be 2.5 years.
Edit: This SQL query contains several approaches to calculate the date difference:
I think that division by 365.2425 is not a good way to do this. No division can to this completely accurately (using 365.25 also has issues).
I know the following script calculates an accurate date difference (though might not be the most speedy way):
For comparison:
You might be able to calculate small ranges with division, but why take a chance??
The following script can help to test yeardiff functions (just swap cast(datediff(day,@d1,@d2) / 365.2425 as int) to whatever the function is):
All
datediff()
does is compute the number of period boundaries crossed between to dates. For instancereturns 1.
You'll get a more accurate result if you compute the difference between the two dates in days and divide by the mean length of a calendar year in days over a 400 year span (365.2425):
For instance,
return
14.29461248
— just round it to the desired precision.I have found a better solution. This makes the assumption that the first date is less than or equal to the second date.