문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top