Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate average time difference between two datetime fields per day

I have a taxi database with two datetime fields 'BookedDateTime' and 'PickupDateTime'. The customer needs to know the average waiting time from the time the taxi was booked to the time the driver actually 'picked up' the customer.

There are a heap of rows in the database covering a couple of month's data.

The goal is to craft a query that shows me the daily average.

So a super simple example would be:

BookedDateTime           | PickupDateTime
2014-06-09 12:48:00.000    2014-06-09 12:45:00.000
2014-06-09 12:52:00.000    2014-06-09 12:58:00.000    
2014-06-10 20:23:00.000    2014-06-10 20:28:00.000
2014-06-10 22:13:00.000    2014-06-10 22:13:00.000

2014-06-09 ((-3 + 6) / 2) = average is 00:03:00.000 (3 mins)

2014-06-10 ((5 + 0) / 2) = average is 00:02:30.000 (2.5 mins)

Is this possible or do I need to do some number crunching in code (i.e. C#)?

Any pointers would be greatly appreciated.

like image 816
ChrisCurrie Avatar asked Aug 01 '14 06:08

ChrisCurrie


People also ask

How do you find the difference between two timestamps in days?

To calculate the difference between the timestamps in SQLite, use the JULIANDAY() function for both timestamps, then subtract one from the other. This way, you get the difference in days. The integer part of the difference is the number of full days, and the decimal part represents a partial day.

How do you calculate average daily count?

Divide your sales generated during the accounting period by the number of days in the period to calculate your average daily sales. In the example, divide your annual sales of $40,000 by 365 to get $109.59 in average daily sales.

How do you calculate average timestamp?

For example you have a time of 2:23:42, you can convert this time to hours by multiplying 24 (or multiplying 1440 to minutes, multiplying 86400 to seconds; in other words, we can apply the formula =F2*24 for converting the time to hours, =F2*1440 to minutes, =F2*86400 to seconds), and then change the formula cell to ...


2 Answers

I think this will do :

select Convert(date, BookedDateTime) as Date, AVG(datediff(minute, BookedDateTime, PickupDateTime)) as AverageTime
    from tablename 
    group by Convert(date, BookedDateTime)  
    order by Convert(date, BookedDateTime) 
like image 71
NeedAnswers Avatar answered Oct 15 '22 04:10

NeedAnswers


Using the day of the booked time as the day for reporting:

select
    convert(date, BookedDateTime) as day,
    AVG(DATEDIFF(minute, PickupDateTime, BookedDateTime)) as avg_minutes
from bookings
group by convert(BookedDateTime, datetime, 101) 
like image 30
Bohemian Avatar answered Oct 15 '22 04:10

Bohemian