I have simple table with start_date
and end_date
columns in it. These date values may overlap
id start_date end_date
1 2011-01-01 2012-04-01
2 2012-05-01 2013-10-01
3 2013-09-01 2014-09-01
4 2013-10-01 2014-08-01
5 2013-12-01 2014-11-01
6 2013-09-01 2014-09-01
7 2015-01-01 2015-11-01
Problem is to find sum in months. Example:
id: 2,3,4,5,6
overlap so idea is to take MAX end_date
and MIN start_date
of 2,3,4,5,6
and add date difference of 1, and of 7.
At this time: I've found how to estimate date difference in months:
PERIOD_DIFF( DATE_FORMAT(end_date, '%Y%m') , DATE_FORMAT(start_date, '%Y%m') )
I know that idea here is to:
- Understand whether two dates overlap or not. And if yes, then merge dates accordingly(adjust end and start dates if needed)
- Loop through all dates, estimate date difference in months, sum and return final result.
I've been looking for similar questions and couldn't resolve and issue, would be nice if you could help me. I know it is possible to do using some programming language and estimate it there, but wanted to write it using MySQL query.
Thanks