如何获得dateiff的平均时间?

时间:2015-02-10 17:14:31

标签: sql sql-server sql-server-2012

通过以下查询,我获得了每个的DATEDIFF 记录在表格中。

我如何才能获得所有记录的日期安全的AVG?

我只关心时间。

SELECT 
right('0' + convert(float,datediff 
                    (second, callstartdt,endstartdt)/ 60 % 60), 2) + ':' +
right('0' + convert(float,datediff 
                    (second, callstartdt,endstartdt)% 60),2)  as total_time
FROM times

http://sqlfiddle.com/#!6/f01c6/2

我有sql 2012。

2 个答案:

答案 0 :(得分:1)

你可以在那里放一个AVG()

SELECT 
    right('0' + convert(float,AVG(datediff (second, callstartdt,endstartdt))/ 60 % 60), 2) + ':' 
  + right('0' + convert(float,AVG(datediff (second, callstartdt,endstartdt))% 60),2)  as total_time
FROM times

演示:SQL Fiddle

答案 1 :(得分:0)

with avg_s as (
    select avg(datediff(ss, callstartdt, endstartdt)) as ss from times
)
select
    ss / 86400 as days,
    ss % 86400 / 3600 as hours,
    ss % 3600 / 60 as minutes,
    ss % 60 as seconds,
    concat(
        format(ss / 3600, '00:'), /* could be greater than 24 */
        format(ss % 3600 / 60, '00:'),
        format(ss % 60, '00')
    )
from avg_s

使用datetime的旧hack会让你做这样的事情但是在Sql Server的更高版本中已经弃用了很多它。

select cast(avg(
        cast(cast(endstartdt as datetime) -
        cast(callstartdt as datetime)
    as float)) as datetime)
from times