T-SQL calculating average time

前端 未结 4 1485
走了就别回头了
走了就别回头了 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: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.

提交回复
热议问题