I need to calculate the number of complete years between two dates in sql. The query I am using currently to calculate is
--Date1 > Date2
CASE
WHEN YEAR(Date1) = YEAR(Date2)
THEN DATEDIFF(year, Date2, Date1)
WHEN YEAR(Date1) > YEAR(Date2)
AND MONTH(Date1) >= MONTH(Date2)
AND DAY(Date1) >= DAY(Date2)
THEN DATEDIFF(year, Date2, Date1)
ELSE
DATEDIFF(year, Date2, Date1) - 1
However I need to tweak it somehow so that it considers the time between 1/5/2011 and 30/4/2012 as 1 complete year.
3条答案
按热度按时间h7appiyu1#
Add one day to
Date2
before you compare it:drkbr07n2#
If the goal is to consider 1-year-less-a-day to be a full year, what about simply adding 1 day to your later date? dateadd() should do it.
I don't think that would cause other erroneous calculations...
bbuxkriu3#
This isn't totally accurate, but it's close: It calculates the difference in days, divides by 365.25, then rounds down.