I need to calculate the exact difference between the two dates
For example difference between date1= '2011-06-27' and date2= '2013-06-27' should return 24 months whereas for date1= '2011-06-27' and date2= '2013-06-29' should return 24 months 2 days.
I tried the below logic which is converting the difference into days and dividing by 30 but that gives the wrong out as dividing by 30 across all months is incorrect. Is there a way to achieve this in SQL
-- Sample table T1 with Date1 and Date2 columns
CREATE TABLE T1 (
Date1 DATE,
Date2 DATE
);
-- Insert your actual data
INSERT INTO T1 (Date1, Date2) VALUES ('2011-06-27', '2013-06-27');
-- Calculate the difference in days and convert to months with a fraction
SELECT
Date1,
Date2,
DATEDIFF(DAY, Date1, Date2) AS DaysDifference,
CAST(DATEDIFF(DAY, Date1, Date2) / 30.0 AS DECIMAL(10, 2)) AS MonthsWithFraction
FROM T1;
You'll want to count the number of times a month boundary is crossed, then add the remaining days.
This is written for SQL Server, but it should be similar.
https://dbfiddle.uk/Ajcifhty