DATEDIFF in HH:MM:SS format

前端 未结 6 983
予麋鹿
予麋鹿 2020-12-06 10:29

I need to calculate the total length in terms of Hours, Minutes, Seconds, and the average length, given some data with start time and end time.

For example the resul

6条回答
  •  醉酒成梦
    2020-12-06 11:11

    If you want to do averages, then the best approach is to convert to seconds or fractions of a day. Day fractions are convenient in SQL Server, because you can do things like:

    select avg(cast(endtime - starttime) as float)
    from t
    

    You can convert it back to a datetime using the reverse cast:

    select cast(avg(cast(endtime - starttime as float) as datetime)
    from t
    

    The arithmetic to get the times in the format you want . . . that is a pain. You might consider including days in the final format, and using:

    select right(convert(varchar(255), , 120), 10)
    

    To get the hours exceeding 24, here is another approach:

    select cast(floor(cast( as float)*24) as varchar(255))+right(convert(varchar(255), , 120), 6)
    

    It uses convert for minutes and seconds, which should be padded with 0s on the left. It then appends the hours as a separate value.

提交回复
热议问题