如何在MySQL中创建记录之间的平均时差?

时间:2011-09-05 19:30:06

标签: mysql

我希望在设备连接之间创建平均时差。

我现在有了这个查询,感谢ajreal。我现在需要做的是创建和发布每个设备记录之间的平均时间。

select device, count(*) as cnt, max(time)
from database.table
group by device
having cnt>1
order by device;

我一直在玩TIMEDIFF,但我需要所有设备记录之间的平均值,而不仅仅是最小值和最大值。

该表的结构如下:

ID, device(string),
data1(int),data2(int), 
time(timestamp), 
data3(int),
data4(int)

我如何实现目标?

这是表格定义。

字段类型空键默认额外

id int(11)NO PRI NULL auto_increment  device varchar(15)NO MUL NULL
 data1 decimal(5,2)YES NULL
 data2 decimal(5,2)YES NULL
 时间戳是YES NULL
 data3 decimal(3,0)YES NULL
 data4 decimal(3,0)YES NULL

感谢您查看我的问题@Chris Henry!

4 个答案:

答案 0 :(得分:2)

您必须将时间戳转换为数字才能绕过它。如果您有平均时间戳,请将其转换回日期。

select device, count(*) as cnt, FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(time)), '%i:%s')
from database.table
group by device
having cnt>1
order by device;

注意:如果你考虑负面时间,你的平均值是显而易见的!如果你不这样做,那么用脚本语言(php,c#,ruby ......)计算它是个更好的主意。

average := avg(ts1–ts2, ts2-ts3, ts3-ts4)
= (ts1–ts2 + ts2-ts3 + ts3-ts4)/3
= (ts4-ts1)/3

概括:

average = (last entry - first entry) / (number of entries - 1)

答案 1 :(得分:1)

这将为您提供每个事件的时间差异(安全地忽略 第一个):

SELECT 
  device, 
  TIME_TO_SEC(TIMEDIFF(time1, time0)) as diff
FROM 
  table t0
JOIN table t1 
  ON t0.device = t1.device
  AND t0.time < t1.time
LEFT JOIN table t2
  ON t1.device = t2.device
    AND t2.time < t1.time
    AND t2.time > t1.time
WHERE
  t2.id IS NULL

然后取出设备的平均值。

SELECT device, AVG(diff)
FROM (
   put the above query here
) AS tbl
GROUP BY device

答案 2 :(得分:0)

SELECT device
     , COUNT(*)   AS cnt
     , TIME_FORMAT( TIMEDIFF(MAX(`time`), MIN(`time`))  / (COUNT(*)-1) 
                  , '%H:%i:%s:%f' ) 
       AS avgTimeDiff
FROM database.table
WHERE `time` IS NOT NULL
GROUP BY device
HAVING COUNT(*) > 1
ORDER BY device

答案 3 :(得分:-2)