I'm having a problem with selecting rows only with maximum values from column ProblemsAmount, which represents COUNT(*) from inner query. It looks like:
PersonID | PersonName | ProblemID | ProblemsAmount
1 | Johny | 1 | 10
1 | Johny | 2 | 5
1 | Johny | 3 | 18
2 | Sara | 4 | 2
2 | Sara | 5 | 12
3 | Katerina | 6 | 17
3 | Katerina | 7 | 2
4 | Elon | 8 | 20
5 | Willy | 9 | 6
5 | Willy | 10 | 2
What I want to get:
PersonID | PersonName | ProblemID | ProblemsAmount
1 | Johny | 3 | 18
2 | Sara | 5 | 12
3 | Katerina | 6 | 17
4 | Elon | 8 | 20
5 | Willy | 9 | 6
The code I have right now:
SELECT A.PersonID,
A.PersonName,
A.ProblemID,
MAX(A.ProblemsCounter) AS ProblemsAmount
FROM (SELECT Person.PersonId AS PersonID,
Person.Name AS PersonName,
Problem.ProblemId AS ProblemID,
COUNT(*) AS ProblemsCounter
FROM Person,
Problem
WHERE Problem.ProblemId = Person.ProblemId
GROUP BY Person.PersonId, Person.Name, Problem.ProblemId
) A
GROUP BY A.PersonID, A.PersonName, A.ProblemID
ORDER BY A.PersonName, ProblemsAmount DESC;
Inner query returns the same thing as outer does, I'm confused with MAX function. It doesn't work and I don't understand why. I tried to fix it using HAVING, but it wasn't successfully.
Thanks in advance.