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

SQL:tæl alle poster med fortløbende forekomst af samme værdi for hvert enhedssæt og returner det højeste antal

Dette er en form for huller-og-øer. Du kan bruge en forskel på rækkenumre for at få øerne:

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);

Brug derefter et andet lag af vinduesfunktioner for at få det maksimale:

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;



  1. Ukendt MySQL-servervært

  2. Sådan forbedres MySQL AWS-ydeevne 2X over Amazon RDS til samme pris

  3. SQL Server Triggere – Del 2 DDL &LOGON Triggere

  4. Hvordan tilføjer jeg en kontrolbegrænsning i en Rails-migrering?