简体   繁体   English

MySql:计算行,直到值更改

[英]MySql: Counting rows until value changes

I know how to count rows with a certain value, but how do I count the rows up until that value changes? 我知道如何对具有特定值的行进行计数,但是如何计数直到该值更改为止的行?

For instance: 例如:

1 cat
2 cat
3 cat
4 dog
5 dog
6 cat
7 cat

How would I count the first three cats without counting the last two cats? 我如何计算前三只猫而不计算最后两只猫?

You can find the id of the first thing that is not a cat and count the ids less than that: 您可以找到不是猫的第一件事的ID,并计算少于该ID的ID:

select count(*)
from t
where id < (select min(t2.id) from t t2 where t2.value <> 'cat');

You can do something like this: 您可以执行以下操作:

SELECT @val := 1;
SELECT COUNT(IF(@val = 1 AND animal = 'cat', @val := 1, @val := NULL)) cnt FROM animals;

What this does is: 这是什么:

  • Initialize a variable @val to 1. 将变量@val初始化为1。
  • For every row that matches the if condition, return 1; 对于与if条件匹配的每一行,返回1;否则,返回0。 else return NULL. 否则返回NULL。
  • Count the number of (non-NULL) rows. 计算(非NULL)行的数量。

That will give you the count you need. 那将给您您需要的计数。 If you need the actual values of the rows, you can do something like this: 如果您需要这些行的实际值,则可以执行以下操作:

SELECT @val := 1;
SELECT * FROM (
        SELECT id, animal, IF(@val = 1 AND animal = 'cat', @val := 1, @val := NULL) ok FROM animals
    ) _animals WHERE ok = 1;

What the if statement does is, as long as @val = 1 (the initial condition) and you're looking at a cat, set @val to 1 and return 1. As soon as the animal is no longer a cat, @val becomes NULL, which means all future rows will also return NULL (because @val will no longer be 1). if语句的作用是,只要@val = 1 (初始条件)并且您在看猫,请将@val设置为1并返回1。一旦动物不再是猫,则@val变为NULL,这意味着所有将来的行也将返回NULL(因为@val将不再为1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM