2014-04-02 33 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; 
相關問題