Avg Time difference in mysql

后端 未结 4 2215
清歌不尽
清歌不尽 2021-02-12 19:04

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

4条回答
  •  别那么骄傲
    2021-02-12 19:43

    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!)

提交回复
热议问题