SQL Server:小时和分钟平均值

时间:2011-09-27 08:36:53

标签: sql sql-server

在SQL Server中,我在表上有一个开始时间列,例如:

2011-09-18 08:06:36.000
2011-09-19 05:42:16.000
2011-09-20 08:02:26.000
2011-09-21 08:37:24.000
2011-09-22 08:22:20.000
2011-09-23 11:58:27.000
2011-09-24 09:00:48.000
2011-09-25 06:51:34.000
2011-09-26 06:09:05.000
2011-09-27 08:25:26.000
...

我的问题是,如何获得平均时间和分钟?我想知道这份工作的平均开始时间是多少。 (例如07:22)

我尝试过这样的事情,但没有奏效:

select CAST(AVG(CAST(DATEPART(HH, START_TIME)AS float)) AS datetime) FROM

感谢。

2 个答案:

答案 0 :(得分:1)

declare @T table(StartTime datetime)

insert into @T values
('2011-09-18 08:06:36.000'),
('2011-09-19 05:42:16.000'),
('2011-09-20 08:02:26.000'),
('2011-09-21 08:37:24.000'),
('2011-09-22 08:22:20.000'),
('2011-09-23 11:58:27.000'),
('2011-09-24 09:00:48.000'),
('2011-09-25 06:51:34.000'),
('2011-09-26 06:09:05.000'),
('2011-09-27 08:25:26.000')

;with C(Sec) as
(
  select dateadd(second, avg(datediff(second, dateadd(day, datediff(day, 0, StartTime), 0), StartTime)), 0)
  from @T
)
select convert(char(5), dateadd(minute, case when datepart(second, C.Sec) >= 30 then 1 else 0 end, C.Sec), 108)
from C
-----
08:08

答案 1 :(得分:0)

试试这个:

select  CAST((SUM(DATEPART(HH, START_TIME) * 60 + DATEPART(MI, START_TIME))/COUNT(*))/60 AS VARCHAR(10)) + ':' + CAST((SUM(DATEPART(HH, START_TIME) * 60 + DATEPART(MI, START_TIME))/COUNT(*))%60 AS VARCHAR(10)) 
FROM.....