sql >> Base de Datos >  >> RDS >> Mysql

MySql:calcule la diferencia de tiempo para varias filas

Obtenga el intervalo promedio en segundos:

select (to_seconds(max(job_started)) - to_seconds(min(job_started))) / (count(*) - 1) as average_interval_seconds
from JobTable
where date(job_started) >= '2016-07-01'
  and date(job_started) <= '2016-07-31'
;

Obtenga todos los intervalos en segundos:

select to_seconds((
  select t2.job_started
  from JobTable t2
  where t2.job_started > t1.job_started
    and date(t2.job_started) <= '2016-07-31'
  limit 1
)) - to_seconds(t1.job_started) as interval_seconds
from JobTable t1
where date(t1.job_started) >= '2016-07-01'
  and date(t1.job_started) <= '2016-07-31'
  and t1.job_started <> (
    select job_started
    from JobTable
    where date(job_started) <= '2016-07-31'
    order by job_started desc
    limit 1
  )
;

http://sqlfiddle.com/#!9/1f8dc3/2