计算表中两个连续值的出现总次数

时间:2015-01-01 17:40:12

标签: mysql sql database

我的表结构

+----+--------+
| id | status |
+----+--------+
|  1 |     10 |
|  2 |     21 |
|  3 |     22 |
|  4 |     29 |
|  5 |     30 |
|  6 |     32 |
|  7 |     33 |
|  8 |     21 |
|  9 |     22 |
| 10 |     23 |
| 11 |     21 |
| 12 |     22 |
| 13 |     23 |
+----+--------+

我想计算状态22在状态21之后到来的总次数。

在这种情况下,查询应返回3.

sql fiddle

3 个答案:

答案 0 :(得分:2)

只需使用Self JoinConditional Aggregate

SELECT Sum(CASE WHEN a.status = 22 AND b.status = 21 THEN 1 END) As Stat_Count
FROM   testTable a
       LEFT OUTER JOIN testTable b
              ON a.id = b.id + 1 

SQLFIDDLE DEMO

答案 1 :(得分:1)

如果您的ID中有空白,您可以使用子查询来检查22行的先前状态是否为21

select count(*)
from testtable a
where a.status = 22 and (select status from testtable b 
  where b.id < a.id order by id desc limit 1) = 21

http://sqlfiddle.com/#!2/9d567/2

另一种方法是在派生表中获取状态为22的前一行行的所有id,然后加入id以计算有多少具有21的状态

select count(*) from (
    select max(b.id) max_b_id
    from testtable a join testtable b on b.id < a.id
    where a.status = 22
    group by a.id
) t1 join testtable a on a.id = t1.max_b_id
where a.status = 21

答案 2 :(得分:0)

我试图在php中解决它

$q="";
$q= mysqli_query("select *from testTable");
while($r=mysqli_fetch_assoc($q)){
  $rows[]=$r;
}
$success=0;
for ($i=0;$i<count($rows);$i++){

    if($rows[$i]['status']==21 and $rows[$i+1]['status']==22 ){
    $success+=1;
    }
}

echo $success;