我试图获得具有连续值的行数的最高计数。例如,如果下面是一个表格,我计算了连续'A'的总数,我会得到5。
- A
- 乙
- 乙
- A
- A
- A
- A
- 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查询中执行此操作的更简洁方法?
答案 0 :(得分:2)
试试这个逻辑,
select top 1 col1 from myTable
group by col1
order by count(col2) desc
答案 1 :(得分:0)
试试这个:
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:)
的参考资料答案 2 :(得分: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;