Count Whole Month Difference Between Two Dates


 create table test (startDate date, endDate date)
insert into test values
('2019-11-04','2019-12-05')
,('2019-11-04','2019-12-04')
,('2019-10-04','2019-12-05')
,('2019-10-04','2019-12-04')
,('2019-09-04','2019-12-05')
,('2019-09-04','2019-12-04')

Select startDate,endDate,
Case when Datediff(month,startDate,endDate)0
then
DATEDIFF(MONTH
, DATEADD(DAY,-DAY(startDate)+1,startDate)
,DATEADD(DAY,-DAY(startDate),endDate))
Else
0
End
from test

drop table test

/*
startDate	endDate	delta
2019-11-04	2019-12-05	1
2019-11-04	2019-12-04	0
2019-10-04	2019-12-05	2
2019-10-04	2019-12-04	1
2019-09-04	2019-12-05	3
2019-09-04	2019-12-04	2
*/
  

https://forums.asp.net/t/2162129.aspx?count+months+query

https://stackoverflow.com/questions/1106945/calculating-number-of-full-months-between-two-dates-in-sql



Leave a comment