rupa
rupa

Reputation: 603

Avg Time difference in mysql

Is there a function to find average time difference in the standard time format in my sql.

Upvotes: 19

Views: 25930

Answers (4)

HoldOffHunger
HoldOffHunger

Reputation: 20891

I was curious if AVG() was accurate or not, the way that COUNT() actually just approximates the value ("this value is an approximation"). After all, let's review the average formula: average = sum / count. So, knowing that the count is accurate is actually really important for this formula!

After testing multiple combinations, it definitely seems like AVG() works and is a great approach. You can calculate yourself to see if it's working with...

SELECT
    COUNT(id) AS count,
    AVG(TIMESTAMPDIFF(SECOND, OrigDateTime, LastDateTime)) AS avg_average,
    SUM(TIMESTAMPDIFF(SECOND, OrigDateTime, LastDateTime)) / (select COUNT(id) FROM yourTable) as calculated_average,
    AVG(TIME_TO_SEC(TIMEDIFF(LastDateTime,OrigDateTime))) as timediff_average,
    SEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF(LastDateTime, OrigDateTime)))) as date_display
FROM yourTable

Sample Results:

             count: 441000
       avg_average: 5045436.4376
calculated_average: 5045436.4376
  timediff_average: 5045436.4376
      date_display: 1401:30:36

Seems to be pretty accurate!

This will return:

  • count: The count.
  • avg_average: The average based on AVG(). (Thanks to Eric for their answer on this!)
  • calculated_average: The average based on SUM()/COUNT().
  • timediff_avg: The average based on TIMEDIFF(). (Thanks to Andrew for their answer on this!)
  • date_display: A nicely-formatted display version. (Thanks to C S for their answer on this!)

Upvotes: 6

C S
C S

Reputation: 153

In order to get actual averages in the standard time format from mysql I had to convert to seconds, average, and then convert back:

SEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF(timeA, timeB))))

If you don't convert to seconds, you get an odd decimal representation of the minutes that doesn't really make any sense (to me).

Upvotes: 13

Andrew
Andrew

Reputation: 1178

What I like to do is a

SELECT count(*), AVG(TIME_TO_SEC(TIMEDIFF(end,start)))
FROM
  table

Gives the number of rows as well...

Upvotes: 11

Eric
Eric

Reputation: 95133

You can use timestampdiff to find the difference between two times.

I'm not sure what you mean by "average," though. Average across the table? Average across a row?

If it's the table or a subset of rows:

select
    avg(timestampdiff(SECOND, startTimestamp, endTimestamp)) as avgdiff
from
    table

The avg function works like any other aggregate function, and will respond to group by. For example:

select
    col1,
    avg(timestampdiff(SECOND, startTimestamp, endTimestamp)) as avgdiff
from
    table
group by col1

That will give you the average differences for each distinct value of col1.

Hopefully this gets you pointed in the right direction!

Upvotes: 23

Related Questions