Mysql中的重复和分组值

时间:2017-05-19 00:57:24

标签: mysql count

如果计算值0在表格中重复3次或更多次(在下一行中重复常数),如何计算值0的重复次数

在这种情况下,值0将重复超过3次。

+-----------+-------+---------------------+
| 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 |
+-----------+-------+---------------------+

1 个答案:

答案 0 :(得分:1)

使用用户定义的变量将状态从一行保持到下一行。使用一个变量@zerocount来计算连续的零速度;它会在speed != 0时重置为0,并在speed = 0时递增。每当遇到非零值时,另一个变量@counter会递增,因此所有连续的零都将在同一个@counter组中。

然后,为了找出零的运行时间,我们使用按MAX(zerocount)分组的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