mysql按顺序计数零

时间:2015-05-12 11:14:19

标签: mysql sql

我有mysql数据库,我需要按顺序获取零个数,并从第一个零开始打印所有日期,所以例如我有一个这样的表

id, date, impuls_count
1, '12-05-15 12:00:00', 60
2, '12-05-15 12:01:00', 0
3, '12-05-15 12:02:00', 0
4, '12-05-15 12:03:00', 49
5, '12-05-15 12:04:00', 0
6, '12-05-15 12:05:00', 0
7, '12-05-15 12:06:00', 0
8, '12-05-15 12:07:00', 0
9, '12-05-15 12:08:00', 30
10, '12-05-15 12:09:00', 0

这应该得到如下结果:

'12-05-15 12:01:00', 2
'12-05-15 12:04:00', 4
'12-05-15 12:09:00', 1

我试图自己解决它,但我的查询工作很慢(我在表中有5000行),有时会打印两行

SELECT qwe.date, ile
    FROM (SELECT  p.date,
         (SELECT COUNT(*)
            FROM performance_v2
                WHERE date > p.date
                AND date <
                    (SELECT MIN(date)
                    FROM performance_v2
                        WHERE date > p.date AND impuls_count > 0)) ile
          FROM performance_v2 p
              WHERE p.impuls_count > 0
              AND (date(p.date)
                BETWEEN  '2015-05-08%'
                AND  '2015-05-08%')
                AND (time(p.date)
        between '14:00:00' and '22:00:00')
    ORDER BY 1) qwe
WHERE ile > 0

1 个答案:

答案 0 :(得分:1)

在MySQL中,使用变量最容易解决。我的想法是每次impuls_count的值发生变化时都有一个计数器增量。这定义了一组共同​​的值。然后,您可以过滤值并进行聚合以获得所需内容:

select min(date), count(*)
from (select t.*,
             (@g := if(@ic = impuls_count, @g,
                       if(@ic := impuls_count, @g + 1, @g + 1)
                      )
             ) as grp
      from table t cross join
           (select @ic := 0, @g := 0)
      order by id
     ) t
where impuls_count = 0
group by grp