T-SQL计算平均时间

use*_*645 14 t-sql time integer dataformat sql-server-2008

我在计算平均时间时遇到问题.情况就是这样:我有多行,每行都有时间格式的数据,所以我需要计算所有行的平均时间并将其与行数相乘但当然我的数据格式有问题,因为我需要将时间乘以整数

有人可以帮我提一些建议吗?thnx这是一些数据:

times
00:00:00.7400000
00:00:01.1870000
00:00:00.6430000
00:00:00.6100000
00:00:12.9570000
00:00:01.1000000
00:00:00.7400000
00:00:00.5300000
00:00:00.6330000
00:00:01.6000000
00:00:02.6200000
00:00:01.0300000
00:00:01.9630000
00:00:00.9800000
00:00:01.0170000
00:00:00.7600000
00:00:00.7130000
00:00:00.9730000
00:00:01.0000000
00:00:01.0530000
00:00:02.9400000
00:00:00.8200000
00:00:00.8400000
00:00:01.1800000
00:01:25.8230000
00:00:01.0000000
00:00:00.9700000
00:00:01.2930000
00:00:01.3270000
00:00:13.5570000
00:00:19.3170000
00:00:58.2730000
00:00:01.6870000
00:00:18.7570000
00:00:42.8570000
00:01:12.3770000
00:00:01.2170000
00:00:09.9470000
00:00:01.4730000
00:00:00.9030000
00:00:01.0070000
00:00:01.1100000
00:00:01.6270000
00:00:05.0570000
00:00:00.6570000
00:00:00.7900000
00:00:03.2930000
00:00:00.8600000
00:00:01.0330000
00:00:00.9300000
00:00:00.8730000
00:00:00.9600000
00:00:00.8070000
NULL
Run Code Online (Sandbox Code Playgroud)

因此,根据这些数据,需要平均时间或/和该数据的总和

Tar*_*ryn 13

您应该可以使用类似于以下内容的内容:

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;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo.

该转换times数据的datetime,那么float这样你就可以得到avg/ sum,那么你转换值回datetime终于time


Aar*_*and 11

你可以通过做一堆日期算术来做到这一点:

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;
Run Code Online (Sandbox Code Playgroud)

但是,您应该做的不是TIME用来存储间隔/持续时间.TIME用于存储某个时间点(例如,如果您需要存储超过24小时,则会发生故障).相反,您应该存储事件的开始和结束时间.如果您有两个端点,则可以随时计算持续时间(和平均持续时间).