Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate average time between two datetimes across all records?

Each record has a started_at and completed_at datetime field. To calculate the time it took someone to start and complete is obviously easy.

But what I need to do is calculate an average time from start to complete for ALL records.

Ultimately want to be able to say "It takes, on average, X amount of time to start and complete."

I'm running Rails 3.0.6, in case there's some functionality already built in with that.

Also, it's a Postgresql database, but ideally this would work across other databases.

like image 316
Shpigford Avatar asked Dec 14 '25 16:12

Shpigford


1 Answers

A Pure SQL solution would be:

SELECT AVG(TotTime)
FROM (SELECT DateDiff(minute, started_at, completed_at) as 'TotTime'
      FROM MyTable
      WHERE <stuff>) as SubQuery

You can change the part in the DateDiff function to be whatever you need (hours, seconds, milliseconds, etc).

like image 147
JNK Avatar answered Dec 17 '25 21:12

JNK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!