title: Merge intervals in SQL - strange behavior
body: <p>I'm facing a strange issue with MySQL 5.5/5.6.
  I've implemented a classic merge intervals algorithm in SQL, but it's not working as expected with some rows. I used <a href="https://stackoverflow.com/questions/8451925/merging-intervals-in-one-pass-in-sql">Merging intervals in one pass in SQL</a> and <a href="https://stackoverflow.com/questions/41924103/most-efficient-way-to-sum-overlapping-datetimes-in-mysql">Most efficient way to sum overlapping datetimes in MySQL</a> as starting references (C++ @ <a href="http://www.geeksforgeeks.org/merging-intervals/" rel="nofollow noreferrer">http://www.geeksforgeeks.org/merging-intervals/</a>)</p>
  
  <p>Anyone able to spot any issue on this? </p>
  
  <pre class="lang-sql prettyprint-override"><code>SELECT MIN(inizio) as inizio, MAX(fine) as fine 
  FROM (
      SELECT 
      @interval_id := IF(attendances.inizio &gt; @interval_end, @interval_id + 1, @interval_id) AS interval_id, 
      @interval_end := IF(attendances.inizio &lt; @interval_end, GREATEST(@interval_end, attendances.fine), attendances.fine) AS interval_end, 
      attendances.inizio, 
      attendances.fine 
      FROM attendances 
      INNER JOIN attendance_sheets ON ( attendance_sheet_id = attendance_sheets.id) 
      ORDER BY attendances.inizio,attendances.fine 
  ) intervals GROUP BY interval_id;
  </code></pre>
  
  <p>From these rows</p>
  
  <p><a href="https://i.stack.imgur.com/ELGtH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ELGtH.png" alt="enter image description here"></a></p>
  
  <p>I get a skipped @interval_id and wrong @interval_end for </p>
  
  <p><a href="https://i.stack.imgur.com/u3oOO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3oOO.png" alt="enter image description here"></a></p>
  
  <p>which results in a wrong merge for 2017-01-26</p>
  
  <p><a href="https://i.stack.imgur.com/7kvAe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7kvAe.png" alt="enter image description here"></a></p>
  
  <p>thanks in advance
  nicola</p>