1

I am trying to get the highest count of the number of rows with a consecutive value. For example, if below were a table and I counted the total number of consecutive 'A's I would get 5.

  1. A
  2. B
  3. B
  4. A
  5. A
  6. A
  7. A
  8. A
  9. B

I am trying to find a neat way to do this in SQL. I am trying to do it with PHP but struggling, and have created a messy solution:

   $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;

I am wondering if anyone know a neater way to do this in an SQL query?

MeltingDog
  • 14,310
  • 43
  • 165
  • 295

3 Answers3

2

Try this logic,

select top 1 col1 from myTable
group by col1
order by count(col2) desc
AK47
  • 3,707
  • 3
  • 17
  • 36
  • Thanks, but I am having problems replicating it with my code. Any chance you could throw in an example? – MeltingDog Apr 02 '14 at 10:44
  • Just of the sql query - I am having trouble understanding the purpose of col1 as I only need to work with the col with the values I want to count – MeltingDog Apr 02 '14 at 10:49
  • Ans modified, please check, you can have only one col also in select. – AK47 Apr 02 '14 at 10:52
0

try this :

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 :)

referrence from this post Mysql Counting the consecutive number rows that match

Community
  • 1
  • 1
0

Another Idea:

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;
PbxMan
  • 7,525
  • 1
  • 36
  • 40