user5956820
user5956820

Reputation:

MySql - calculate time difference for multiple rows

I have a table with manufacturing assembly data, including timestamps. I'm trying to determine the average interval in minutes between 'job' starts.

My query that returns the id and time looks like:

select job_id, job_started from JobTable where job_started >= '2016-07-01' and job_started <= '2016-07-31';

I'm looking for output that would be the difference in time between each row:

15 18 21 14 13

Upvotes: 0

Views: 727

Answers (1)

Paul Spiegel
Paul Spiegel

Reputation: 31772

Get average interval in seconds:

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'
;

Get all intervals in seconds:

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

Upvotes: 1

Related Questions