Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of datetime data type

I am trying to calculate the average of a few rows with a datetime data type (standard datetime format).
How can I do that?

like image 208
alienavatar Avatar asked Oct 07 '11 23:10

alienavatar


3 Answers

Convert the datetime to a float. The SQL standard defines that as the number of days since 1900, so it should be fairly portable. For example:

declare @t table (dt datetime)
insert @t select '1950-01-01'
union all select '1960-01-01'

select cast(avg(cast(dt as float)) as datetime) from @t

This result is1955-01-01. Example at SE Data.

like image 52
Andomar Avatar answered Sep 20 '22 22:09

Andomar


This is how to get the average of a DateTime column in MySql:

create temporary table table_1 (
    aDate DateTime
);

insert into table_1 values
    ('2000-01-01 00:00:00'),
    ('2010-01-01 00:00:00');

select CAST(avg(aDate) as DateTime) from table_1;
-- Result: "2005-01-01 00:00:00"
like image 41
Mosty Mostacho Avatar answered Sep 19 '22 22:09

Mosty Mostacho


In PostgreSQL you could:

SELECT to_timestamp(avg(EXTRACT(EPOCH FROM my_timestamp)))
  FROM my_tbl;

More info in the fine manual here.

like image 33
Erwin Brandstetter Avatar answered Sep 17 '22 22:09

Erwin Brandstetter