time(7)
使用列以毫秒精度计算平均值。
select dateadd(millisecond, avg(datediff(millisecond, onattendance, offattendance)), cast('00:00' as time(7)) )
from t_attendancedetails
该查询用于获取和datediff
之间的毫秒数差异。然后它使用聚合函数来计算以毫秒为单位的平均差异,最后它使用将平均毫秒数添加到value中。onattendance
offattendance
avg
dateadd
time(7)
00:00
参考:
DATEDIFF (Transact-SQL)
DATEADD (Transact-SQL)
AVG (Transact-SQL)
CAST 和 CONVERT (Transact-SQL)
更新:
当计算精度为 的平均值时,time(7)
您需要将时间分成两部分,因为datediff
不dateadd
处理bigint
.
在计算平均值之前将时间差值转换为纳秒time(7)
,然后分两步完成转换,首先是秒,然后是纳秒。
declare @T0 time(7) = '00:00:00'
declare @G bigint = 1000000000
declare @H bigint = 100
select dateadd(nanosecond, cast(right(T.A, 9) as int), dateadd(second, T.A / @G, @T0))
from
(
select avg(
@G * datediff(second, @T0, offattendance) + @H * right(offattendance, 7) -
@G * datediff(second, @T0, onattendance ) + @H * right(onattendance, 7)
)
from t_attendancedetails
) as T(A)