Skip to content
Advertisement

SQL Count Years on FromDATE to ToDate fields

Suppose i have

> ID              FromDate          ToDate 
> --              --------           -------
> 1               01/01/2005         30/6/2007
> 2               01/01/2008         31/12/2009

I want to count the years that are included on this 2 rows. Here is 1,5 years for the first row + 2 years from second row = Total of 3,5 years. How can i do this with SQL?

Advertisement

Answer

I would recommend using 365.25 for the days in the SQL DateDiff function to avoid issues with leap year.

select 
  SUM((DATEDIFF(d, FromDate, ToDAte)) / 365.25) as 'years-count'
from 
  mytableofdates
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement