Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an average of dates in MySQL?

Tags:

How can I make an average between dates in MySQL? I am more interested in the time values, hours and minutes.

On a table with:

| date_one   | datetime | | date_two   | datetime | 

Doing a query like:

 SELECT AVG(date_one-date_two) FROM some_table WHERE some-restriction-applies; 

Edit:

The AVG(date1-date2) works but I have no clue what data it is returning.

like image 477
fmsf Avatar asked Jun 20 '09 16:06

fmsf


People also ask

Can you take average of dates in SQL?

There are several types of date/time averaging in SQL. You can either average the date/time stamp as a whole, the date part of the date/time stamp, or the time portion of the date/time stamp.

How do I get AVG in MySQL?

MySQL AVG() function retrieves the average value of a given expression. If the function does not find a matching row, it returns NULL. Where expr is a given expression. The DISTINCT option can be used to return the average of the distinct values of expr.

How do I find the average of each row in SQL?

For example, 2+4+4+6+6+8 is 30 divided 6 which results in an average of 5. This is the basic syntax for the AVG function: SELECT AVG(column_name) FROM table_name; In this example, we have a table called students , with columns of id , name , date , and scores .

How do you find the average of time in SQL?

To calculate this average, you can use AVG command. – Averages per minute: to obtain the averages per minute, you must retrieve E3TimeStamp's seconds and milliseconds. To do so, multiply this field by 24 (to convert the time base into hours), and then by 60 (to convert it into minutes).


2 Answers

This seems a bit hackish, but will work for dates beteen ~ 1970 and 2030 (on 32 bit arch). You are essentially converting the datetime values to integer, averaging them, and converting the average back to a datetime value.

SELECT     from_unixtime(         avg(             unix_timestamp(date_one)-unix_timestamp(date_two)         )     ) FROM     some_table WHERE     some-restriction-applies 

There is likely a better solution out there, but this will get you by in a pinch.

like image 166
gahooa Avatar answered Sep 21 '22 18:09

gahooa


select avg(datediff(date1,date2)) select avg(timediff(datetime,datetime)) 
like image 40
Mysql Guru Avatar answered Sep 20 '22 18:09

Mysql Guru