mysql - 计算正连续值

时间:2013-12-31 13:58:38

标签: mysql numbers

记录:

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

我需要知道连续多少次我有一个正数,所以在这种情况下我们有: 2(连续正数) 1(连续正数) 2(连续正数)

我想要的最终结果是用表格显示输出,告诉我表格中有多少时间我们有1个连续数字,2个连续数字,3个连续数字,......

所以像这样的表:

表格结构:

consecutive number
value

数据:

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)

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

试试这个:

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
;

演示: - &gt; http://www.sqlfiddle.com/#!2/75fa7/8