[英]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.