RonEskinder RonEskinder -4 years ago 75
MySQL Question

Repeated and grouped values in Mysql

How to calculate how many times the value 0 is repeated in a table only if that value is constant by 3 or more times (constant being repeated in next row)

in this case it would be 2 occasions that the value 0 is repeated more than 3 times.

+-----------+-------+---------------------+
| idDataGps | speed | eventDate |
+-----------+-------+---------------------+
| 143483 | 56 | 2017-05-18 08:42:05 |
| 143484 | 0 | 2017-05-18 08:42:11 |
| 143485 | 0 | 2017-05-18 08:42:20 |
| 143486 | 0 | 2017-05-18 08:42:35 |
| 143487 | 43 | 2017-05-18 08:42:40 |
| 143488 | 44 | 2017-05-18 08:42:50 |
| 143489 | 48 | 2017-05-18 08:43:05 |
| 143490 | 24 | 2017-05-18 08:43:14 |
| 143491 | 34 | 2017-05-18 08:43:16 |
| 143492 | 9 | 2017-05-18 08:43:20 |
| 143493 | 14 | 2017-05-18 08:43:36 |
| 143494 | 0 | 2017-05-18 08:44:06 |
| 143495 | 0 | 2017-05-18 08:44:21 |
| 143496 | 0 | 2017-05-18 08:46:06 |
| 143497 | 0 | 2017-05-18 08:48:36 |
| 143498 | 0 | 2017-05-18 08:48:42 |
+-----------+-------+---------------------+

Answer Source

Use user-defined variables to keep state from one row to the next. Use one variable @zerocount to count consecutive zero speeds; it gets reset back to 0 whenever speed != 0, and increments whenever speed = 0. Another variable @counter gets incremented whenever a non-zero value is encountered, so all the consecutive zeroes will be in the same @counter group.

Then to find out how long the run of zeroes is, we use MAX(zerocount) grouped by counter.

SELECT COUNT(*) FROM (
    SELECT counter, MAX(zerocount) AS maxcount
    FROM (
        SELECT speed, IF(speed = 0, @zerocount := @zerocount+1, @zerocount := 0) as zerocount,
            IF(speed != 0, @counter := @counter + 1, @counter) AS counter
        FROM (SELECT speed FROM yourTable ORDER BY eventDate) AS t
        CROSS JOIN (SELECT @counter := 0, @zerocount := 0) AS var
    ) AS x
    GROUP BY counter
) AS y
WHERE maxcount >= 3

DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download