How to get an item in SQL if it matches a conditional based on many rows?
To obtain a unique list of names:
GROUP BY name
To restrict the result to names with at least one grade of 'A'
HAVING SUM(grade = 'A') > 0
and also with no grade of 'F'
AND SUM(grade = 'F') = 0
The final SQL for MySQL (Fiddle):
SELECT name
FROM grades
GROUP BY name
HAVING SUM(grade = 'A') > 0
AND SUM(grade = 'F') = 0
;
and as Akina mentions, because MySQL treats 0 as false and non-0 as true, this is equivalent to:
SELECT name
FROM grades
GROUP BY name
HAVING SUM(grade = 'A')
AND NOT SUM(grade = 'F')
;
For PG, a similar approach is (Fiddle), which is also fine for MySQL:
SELECT name
FROM grades
GROUP BY name
HAVING SUM(CASE WHEN grade = 'A' THEN 1 ELSE 0 END) > 0
AND SUM(CASE WHEN grade = 'F' THEN 1 ELSE 0 END) = 0
;
or for just PG:
SELECT name
FROM grades
GROUP BY name
HAVING SUM((grade = 'A')::int) > 0
AND SUM((grade = 'F')::int) = 0
;