[英]SQL: Way to get highest count of consecutive rows with same value?
我試圖獲得具有連續值的行數的最高計數。 例如,如果下面有一張表,我計算了連續的'A'的總數,我將得到5。
- 一種
- 乙
- 乙
- 一種
- 一種
- 一種
- 一種
- 一種
- 乙
我試圖找到一種在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 :)
另一個想法:
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.