SQL:获得具有相同值的连续行的最高计数的方法?

时间:2014-04-02 10:32:34

标签: php mysql sql

我试图获得具有连续值的行数的最高计数。例如,如果下面是一个表格,我计算了连续'A'的总数,我会得到5。

  
      
  1. A
  2.   
  3.   
  4.   
  5. A
  6.   
  7. A
  8.   
  9. A
  10.   
  11. A
  12.   
  13. A
  14.   
  15.   

我正在尝试在SQL中找到一种巧妙的方法。我正在尝试用PHP做但却苦苦挣扎,并创建了一个混乱的解决方案:

   $streaksql = "SELECT * FROM `mytable`";
   $streaksql = $modx->query($streaksql);

   $outcomecounter = 0;
   $highestoutcome = 0;

     while ($streak = $streaksql->fetch(PDO::FETCH_ASSOC)) {

                    $outcome = $row['outcome'];

                    if($outcome == 'A'){
                        $outcomecounter = $outcomecounter +1;

                        if($outcomecounter > $highestoutcome){
                            $highestoutcome = $outcomecounter;
                        }

                    }
                    else {
                        $outcomecounter = 0;
                    }  
                };//WHILE

echo $highestoutcome;

我想知道是否有人知道在SQL查询中执行此操作的更简洁方法?

3 个答案:

答案 0 :(得分:2)

试试这个逻辑,

select top 1 col1 from myTable
group by col1
order by count(col2) desc

答案 1 :(得分:0)

试试这个:

select COUNT(*)+1
FROM your_table a1
where value=(select value from your_table where your_table.id<a1.id order by id desc LIMIT 1) AND value= 'A'

CMIIW:)

此帖Mysql Counting the consecutive number rows that match

的参考资料

答案 2 :(得分:0)

另一个想法:

SELECT outcome, max(Amount) from (
    SELECT  outcome, 
    IF(@a =outcome, @b := @b+1, @b := 1) as "Amount",
    @a := outcome 
    FROM mytable
    WHERE false = (@b:=0)
    AND outcome = 'A'    
) as test
GROUP by outcome;