Average of datetime data type

与世无争的帅哥 提交于 2019-12-23 09:17:51

问题


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


回答1:


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.




回答2:


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"



回答3:


In PostgreSQL you could:

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

More info in the fine manual here.



来源:https://stackoverflow.com/questions/7693878/average-of-datetime-data-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!