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
.
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
.AVG
on Time
,类型不支持,Time
因此您必须先转换Time
为毫秒.Time
类型Arithmetic overflow error converting expression to data type int
你可以将结果转换DateAdd
为a BigInt
.或者,您可以使用seconds
而不是milliseconds
在DateDiff
应该工作的函数中,除非您的结果集过大.SO来源:
归档时间: |
|
查看次数: |
8620 次 |
最近记录: |