Mysql
 sql >> Database >  >> RDS >> Mysql

SQL:conta tutti i record con occorrenza consecutiva dello stesso valore per ogni dispositivo impostato e restituisce il conteggio più alto

Questa è una forma di lacune e isole. Puoi utilizzare una differenza di numeri di riga per ottenere le isole:

select device_id, speed, count(*) as num_times
from (select t.*,
             row_number() over (partition by device_id order by datetime) as seqnum,
             row_number() over (partition by device_id, speed order by datetime) as seqnum_s
      from t
     ) t
group by device_id, speed, (seqnum - seqnum_s);

Quindi, per ottenere il massimo, usa un altro livello di funzioni della finestra:

select device_id, speed, num_times
from (select device_id, speed, count(*) as num_times,
             row_number() over (partition by device_id order by count(*) desc) as seqnum
      from (select t.*,
                   row_number() over (partition by device_id order by datetime) as seqnum,
                   row_number() over (partition by device_id, speed order by datetime) as seqnum_s
            from t
           ) t
      group by device_id, speed, (seqnum - seqnum_s)
     ) ds
where seqnum = 1;