簡體   English   中英

SQL:如何獲得具有相同值的連續行的最高計數?

[英]SQL: Way to get highest count of consecutive rows with same value?

我試圖獲得具有連續值的行數的最高計數。 例如,如果下面有一張表,我計算了連續的'A'的總數,我將得到5。

  1. 一種
  2. 一種
  3. 一種
  4. 一種
  5. 一種
  6. 一種

我試圖找到一種在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查詢中這樣做的更簡潔的方法?

試試這個邏輯,

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

嘗試這個 :

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計數匹配的連續數字行

另一個想法:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM