Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

Count rows until value in column changes mysql

So I have a table with a column that has a true or false (0 or 1) value. I want to know the count of consecutive 0s before I hit a 1. So for example if I had the following time ASC:

0
0
1
0
1
0
0
0

The return number of last consecutive 0s would be 3. I've been looking for a way to count until the value changes but so far no luck. Any thoughts?

EDIT:

here's a clearer example of my table

|id|counter|user_id|
--------------------
|0 |0      |3      | 
--------------------
|1 |0      |3      | 
--------------------
|2 |1      |3      | 
--------------------
|3 |0      |3      | 
--------------------
|4 |1      |3      | 
--------------------
|5 |0      |3      | 
--------------------
|6 |1      |8      | 
--------------------
|7 |0      |3      | 
--------------------
|8 |0      |3      | 
--------------------

for user_id = 3, the result would be 3

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your time column seems to specify the ordering. Then the number of zeros at the end would be:

select count(*)
from table t
where t.col = 0 and
      t.time > (select max(t2.time) from table t2 where t2.col = 1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...