SQL: count all records with consecutive occurrence of same value for each device set and return the highest count

后端 未结 1 933
长发绾君心
长发绾君心 2021-01-17 05:39

I want to find out how many times a particular value occured consecutively for a particular partition and then display the higher count for that partition.

For Examp

相关标签:
1条回答
  • 2021-01-17 06:11

    This is a form of gaps-and-islands. You can use a difference of row numbers to get the islands:

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

    Then, to get the max, use another layer of window functions:

    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;
    
    0 讨论(0)
提交回复
热议问题