text: Q:
  
  Calculate time differences between multiple set of data
  
  This is a data set in a mysql table which is related to a error log of an electronic divice.
  i need to calculate the total down time. 
  time_stamp      error_type  error_status
  1467820110           1           1
  1467820120           2           1                  
  1467820130           3           1
  1467820140           3           0
  1467820150           1           0
  1467820160           2           0
  1467820180           1           1
  1467820185           1           0
  1467820191           2           1
  1467820300           2           0
  1467820302           1           1
  1467820404           3           1
  1467820408           3           0
  1467820409           1           0
  
  error_status 1 = error occored
  error_status 0 = error fixed
  
  1st down time 1467820160 - 1467820110 = 50
  2nd down time 1467820185 - 1467820180 = 5
  3rd down time 1467820300 - 1467820191 = 109
  4th down time 1467820409 - 1467820302 = 107
  
  total down time = 50 + 5 + 109 + 107 = 271
  
  How can i write a mySQL compatible SQL statement to achieve this.  
  
  A:
  
  Basically, you need to calculate the number of cumulative errors that have occurred.  Then identify groups where the values are greater than 0.  This can be done by doing a cumulative count of the number of "0"s for the cumulative errors.
  There is a challenge getting the final timestamp.  One trick is to get the next status 0 timestamp for the error.  This acts as an "end".
  Finally, an aggregation get the information for each period:
  select count(*) as num_errors, max(end_timestamp) - min(timestamp)
  from (select t.*,
               (@grp := @grp + if(cume_errors = 0, 1, 0)) as grp
        from (select t.*,
                     (select t2.timestamp
                      from t t2
                      where t2.error_type = t.error_type and
                            t2.error_status = 0 and
                            t2.timestamp > t.timestamp
                      order by t2.timestamp asc
                      limit 1
                     ) as end_timestamp,
                     (@e := @e + if(error_status > 0, 1, -1)) as cume_errors
              from t cross join
                   (select @e := 0) params
              order by timestamp
             ) t cross join
             (select @grp := 0) params
        order by timestamp
       ) t
  where error_status > 0
  group by grp;
  
  You can aggregate over this query to get the total period of downtime.
  Here is a SQL Fiddle.
  
  