I have a table with the following structure
finals(ID, name, result)
CREATE TABLE `finals` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
`result` char(4) DEFAULT NULL,
PRIMARY KEY (`id`)
);
Where:
ID
is an auto increment key,name
is the person's name,result
is either Pass or Fail
Sample data
mysql> select * from finals;
+----+------+--------+
| id | name | result |
+----+------+--------+
| 1 | John | Pass |
| 2 | John | Fail |
| 3 | John | Pass |
| 4 | Kyle | Pass |
| 5 | John | Pass |
| 6 | Kyle | Pass |
| 7 | Kyle | Pass |
| 8 | Kyle | Fail |
+----+------+--------+
8 rows in set (0.00 sec)
Explanation
I am trying to get the names of people who have at least 3 consecutive "Pass". So, the desired result is: "Kyle" Because "Kyle" has 3 cosecutive "Pass", IDs 4, 6, 7.
Note please that I don't care if this sequence is interrupted by a record of other person, but I care if it was interrupted by a record for the same person with "Fail" value in the result.
That is why "John" is not in the desired result. i.e. Although "John" has 3 "pass" in total, they are interrupted with a "Fail", so I want to exclude it from the result.
I Tried this query:
mysql> SELECT name, GROUP_CONCAT(result ORDER BY id) as result_str FROM finals GROUP BY name having result_str LIKE '%Pass,Pass,Pass%';
+------+---------------------+
| name | result_str |
+------+---------------------+
| Kyle | Pass,Pass,Pass,Fail |
+------+---------------------+
1 row in set (0.00 sec)
It works, and this is the desired result. However, I am looking for alternative ways to
- Be more Generic
- avoid the constraints on the length of the result of GROUP_CONCAT.
Thank you in advance.