SQL查询 - 从datetime字段开始的平均时间

Jon*_*ill 3 sql-server datetime

我正在努力解决我认为简单的SQL查询问题.运行SQL Server 2014

我有一个SQL表,"访问":

Id | EntryTime | Duration
Run Code Online (Sandbox Code Playgroud)

我想找到两个日期之间的平均入场时间,同时考虑这些日期之间的所有记录.

所以,如果我的EntryTime日期之间的字段是:

2016-04-28 12:00:00
2016-04-20 10:00:00
2016-04-19 08:00:00
2016-04-17 10:00:00
Run Code Online (Sandbox Code Playgroud)

那么返回的平均时间应该是:

10:00:00
Run Code Online (Sandbox Code Playgroud)

根本不应该考虑日期,它应该以字符串格式或仅返回的方式返回10:00:00.

Igo*_*gor 9

create table mytimes(
   id int identity,
   mydatetime datetime
)

insert into mytimes (mydatetime) values ('2016-04-28 12:00:00')
insert into mytimes (mydatetime) values ('2016-04-20 10:00:00')
insert into mytimes (mydatetime) values ('2016-04-19 08:00:00')
insert into mytimes (mydatetime) values ('2016-04-17 10:00:00')

SELECT Cast(DateAdd(ms, AVG(CAST(DateDiff( ms, '00:00:00', cast(mydatetime as time)) AS BIGINT)), '00:00:00' ) as Time ) 
from mytimes
-- where mydatetime between XXX and YYY

SELECT convert(varchar(8), Cast(DateAdd(ms, AVG(CAST(DateDiff( ms, '00:00:00', cast(mydatetime as time)) AS BIGINT)), '00:00:00' ) as Time )) 
from mytimes
-- where mydatetime between XXX and YYY
Run Code Online (Sandbox Code Playgroud)

output-1 10:00:00.0000000 - 这是一个实际的时间类型,如果需要,您可以执行更多操作

output-2 10:00:00 - 输出为varchar(8)

根据需要添加where子句

步骤包括

  • Time从一个类型转换为一个类型DateTime.
  • 使用AVGon Time,类型不支持,Time因此您必须先转换Time为毫秒.
  • 将毫秒转换回Time类型
  • 为了避免Arithmetic overflow error converting expression to data type int你可以将结果转换DateAdd为a BigInt.或者,您可以使用seconds而不是millisecondsDateDiff应该工作的函数中,除非您的结果集过大.

SO来源: