2014-04-02 31 views
1

我想获得具有连续值的行数的最高计数。例如,如果下面是一个表和我数个连续的“A的总数我会得到5.SQL:获取具有相同值的连续行数最高的方法?

  1. A
  2. A
  3. A

我试图找到一种简洁的方式在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查询来做到这一点?

+1

你的意思是_consecutive_,对吧? – moonwave99

+0

哎呀是的,我愿意 - 谢谢 – MeltingDog

+0

可能重复的[Mysql计数匹配的连续数字行](http://stackoverflow.com/questions/19541762/mysql-counting-the-consecutive-number-rows-that-match) – moonwave99

回答

2

试试这个逻辑,

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

谢谢,但我有问题与我的代码复制它。有什么机会可以抛出一个例子吗? – MeltingDog

+0

所以你想要的PHP代码的例子? – AK47

+0

只是sql查询 - 我无法理解col1的用途,因为我只需要与col一起使用我想要计数的值 – MeltingDog

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; 
相关问题