简体   繁体   中英

SQL - MySQL - average group by and limit problems

I am collecting data from various remote sensors that send their data every so many seconds. I record the name of the remote sensor and the time difference since the last time I received data from that instrument. The data for each instrument comes in a random order and not at set intervals.

The table looks like:

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

The id column is auto incrementing.

What I am trying to do is get the average timediff for each instrument for the last 10 values of each instrument.

the closest I've got is:

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

Obviously this only works for 1 instrument and I'm not convinced the limit is working properly either. I don't know the names of the instruments nor how many I'll be collecting data from.

How do I get the average timediff of the last 10 values for each instrument using SQL?

Somewhat painfully. I think the easiest way is to use variables. The following query enumerates the readings for each instrument:

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;

You can then use this as a subquery to do your calculation:

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;

try using this:tested on less data but should work.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM