T-SQL calculating average time

試著忘記壹切 提交于 2019-12-04 02:00:27

You should be able to use something similar to the following:

select 
  cast(cast(avg(cast(CAST(times as datetime) as float)) as datetime) as time) AvgTime,
  cast(cast(sum(cast(CAST(times as datetime) as float)) as datetime) as time) TotalTime
from yourtable;

See SQL Fiddle with Demo.

This converts the times data to a datetime, then a float so you can get the avg/sum, then you convert the value back to a datetime and finally a time

You can do this by doing a bunch of date arithmetic:

DECLARE @t TABLE(x TIME);

INSERT @t VALUES('00:01:30'),('00:02:25'),('00:03:25');

SELECT CONVERT(TIME, DATEADD(SECOND, AVG(DATEDIFF(SECOND, 0, x)), 0)) FROM @t;

However, what you should be doing is not using TIME to store an interval/duration. TIME is meant to store a point in time (and breaks down if you need to store more than 24 hours, for example). Instead you should store that start and end times for an event. You can always calculation the duration (and the average duration) if you have the two end points.

Assuming you have stored duration in a time field, you could try Datediff function like below to get the sum of durations (or total time). Simply use Avg for average.

Demo: http://sqlfiddle.com/#!3/f8c09/2

select sum(datediff(millisecond,0,mytime)) TotalTime
from t

This may be useful in this and similar scenarios.

Below will convert the date/time to a number of minutes since midnight. In other words time expressed as an integer. You can do an average on that and then convert back to time.

declare @dt datetime = GETDATE();
select DATEDIFF(minute, dateadd(dd, datediff(dd, 0, @dt), 0), @dt);
--DATEDIFF(minute, [date without time i.e. midnight], [date/time of interest])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!