Summing range of dates without counting overlaps in mysql

前端 未结 3 1944
遇见更好的自我
遇见更好的自我 2021-01-26 18:09

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         


        
3条回答
  •  长情又很酷
    2021-01-26 18:23

    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
    

提交回复
热议问题