Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql - count positive consecutive value

Tags:

mysql

numbers

records:

ID | NAME  | VALUE
---|-------|-------
 1 | ALPHA | 5     
 2 | ALPHA | 7        //comment: [2 times positive numbers]
 3 | ALPHA | -4
 4 | ALPHA | 3        //comment: [1 times positive numbers]
 5 | ALPHA | -2
 6 | ALPHA | -3
 7 | ALPHA | 9      
 8 | ALPHA | 3        //comment: [2 times positive numbers]
 9 | ALPHA | -2
10 | ALPHA | -6

I need to know how many consecutive time I have a positive number so in this case we have: 2 (consecutive positive number) 1 (consecutive positive number) 2 (consecutive positive number)

the final result that I want is show output with a table that tell me how many time in table we have 1 consecutive number, 2consecutive numbers, 3consecutive numbers, ...

so a table like this:

table structure:

consecutive number
value

data:

1 | 1 (we have 1 times, 1 consecutive numbers)
2 | 2 (we have 2 times, 2 consecutive numbers)
3 | 0 (we have 0 times, 3 consecutive numbers)
like image 433
user3149423 Avatar asked Aug 30 '26 11:08

user3149423


2 Answers

Try this:

SELECT x consecutive_numbers,
       count(*) how_many_times
FROM (
  SELECT y, max( x ) x
  FROM (
    SELECT
     if( value < 0, @x:=0, @x:=@x+1 ) x,
     if( value < 0, @y:=@y+1, @y ) y,
     value
    FROM table1
    CROSS JOIN (
       select @x:=0, @y:=0
    ) var
    ORDER BY id
  )q
  WHERE value >= 0
  GROUP BY y
) qq
GROUP BY x
;

Demo: --> http://www.sqlfiddle.com/#!2/75fa7/8

like image 56
krokodilko Avatar answered Sep 02 '26 05:09

krokodilko


SELECT peak as consecutive_number, COUNT(*) AS value
FROM (
    SELECT IF(value <= 0 AND @counter > 0, @counter, NULL) AS peak, @counter := IF(value <= 0, 0, @counter+1) AS counter
    FROM (SELECT *
          FROM (SELECT value
                FROM mytable
                ORDER BY id) x
               UNION ALL
               SELECT -1) x -- in case last row is positive
    CROSS JOIN (SELECT @counter := 0) var
) x
WHERE peak IS NOT NULL
GROUP BY peak

DEMO

like image 29
Barmar Avatar answered Sep 02 '26 04:09

Barmar