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-0
I did it my own way checking other answers here on Stackoverflow, it should work:
select sum(months)
from (select t.*,
@time := if(@sum = 0, 0, period_diff(date_format(start_date, '%Y%m'), date_format(@prevtime, '%Y%m'))) as months,
@prevtime := start_date,
@sum := @sum + isstart
from ((select start_date, 1 as isstart
from position t
) union all
(select end_date, -1
from position t
)
) t cross join
(select @sum := 0, @time := 0, @prevtime := 0) vars
order by 1, 2
) t