Question

table: uni(course, symbol) and some other columns... want to select all the courses with the same maximum amount of fails.

my code is returning an empty set. there was a very similar question here but the answer didn't deal with how to get the the maximum value if there are more than one with the same maximum value.

SELECT course, count(symbol) as fails FROM uni WHERE Symbol = 'F' GROUP BY Course having fails = max(fails);

Was it helpful?

Solution

This is a very common mistake among people learning SQL. In most databases, your query would fail, because you cannot take the max() of a count(). I'm surprised that it works in MySQL, but indeed it does (here is the SQL Fiddle).

In any case, you need a subquery for this:

SELECT course, count(symbol) as fails
FROM uni
WHERE Symbol = 'F'
GROUP BY Course
HAVING fails = (SELECT max(fails)
                FROM (SELECT count(symbol) as fails
                      FROM uni
                      WHERE Symbol = 'F'
                      GROUP BY course
                     ) f
               );

Inelegant, but it should work. You can also write the having clause as:

HAVING fails = (SELECT count(symbol) as fails
                FROM uni
                WHERE Symbol = 'F'
                GROUP BY course
                ORDER BY fails DESC
                LIMIT 1
               )

By the way, I have some sympathy for your formulation. SQL claims to be a descriptive language, where the coder describes the output and compiler figures out the best way to execute a query. That ideal is only partially true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top