Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Number of years between dates in Sql

Tags:

sql

sql-server

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.

like image 472
Vijay Ganesh Avatar asked Oct 10 '22 07:10

Vijay Ganesh


1 Answers

Add one day to Date2 before you compare it:

dateadd(day, 1, Date2)
like image 189
Andomar Avatar answered Oct 12 '22 23:10

Andomar