SQL - MySQL - 平均分组和限制问题

时间:2014-12-10 16:33:30

标签: mysql sql

我正在从各种远程传感器收集数据,这些传感器每隔很多秒发送一次数据。我记录了自上次从该仪器接收数据以来远程传感器的名称和时间差。每种仪器的数据按随机顺序排列,而不是按设定的间隔。

表格如下:

id  instname  timediff
 1   inst01     1000
 2   inst02     1100
 3   inst01     1210
 4   inst03      900  
etc.

id列自动递增。

我要做的是获取每种乐器的平均时间长度,以获得每种乐器的最后10个值。

我最接近的是:

SELECT 
    inst AS Instrument, 
    AVG(diff / 1000) AS Average
FROM
    (SELECT 
        instname AS inst, timediff AS diff
    FROM
        log
        WHERE
        instname = 'Inst01' 
    ORDER BY id DESC
    LIMIT 0 , 10) AS two

显然这只适用于1台乐器,我也不相信极限也能正常工作。我不知道仪器的名称,也不知道我将收集多少数据。

如何使用SQL获取每个乐器的最后10个值的平均时间长度?

2 个答案:

答案 0 :(得分:2)

有点痛苦。我认为最简单的方法是使用变量。以下查询列举了每种工具的读数:

select l.*,
       (@rn := if(@i = instname, @rn + 1, 
                  if(@i := instname, 1, 1)
                 )
       ) as rn
from log l cross join
     (select @i := '', @rn := 0)
order by instname, id desc;

然后,您可以将其用作子查询来进行计算:

select instname, avg(timediff)
from (select l.*,
             (@rn := if(@i = instname, @rn + 1, 
                        if(@i := instname, 1, 1)
                       )
             ) as rn
      from log l cross join
           (select @i := '', @rn := 0)
      order by instname, id desc
     ) l
where rn <= 10
group by instname;

答案 1 :(得分:0)

尝试使用此方法:在较少的数据上进行测试,但应该可以正常工作。

SELECT 
    inst AS Instrument, 
     diff AS Average
FROM
    (SELECT 
        t1.instname AS inst,AVG(t1.timediff / 1000) AS diff
    FROM
        inst t1,inst t2
        WHERE
        t1.instname = t2.instname   group by t1.instname ORDER BY t2.id DESC
    LIMIT 0,10
    ) AS two