T-SQL calculating average time

前端 未结 4 1486
走了就别回头了
走了就别回头了 2021-01-03 23:57

I have a problem with calculating average time. This is the case: i have multiple rows, in each row there is data in time format so I need to calculate an average time of al

相关标签:
4条回答
  • 2021-01-04 00:00

    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])
    
    0 讨论(0)
  • 2021-01-04 00:20

    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.

    0 讨论(0)
  • 2021-01-04 00:23

    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

    0 讨论(0)
  • 2021-01-04 00:26

    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
    
    0 讨论(0)
提交回复
热议问题