Reputation: 33
select h.hacker_id, name, count(challenge_id) as total from Challenges c inner join Hackers h on h.hacker_id=c.hacker_id group by h.hacker_id, name
having total not in
(select count(challenge_id) as cnt from Challenges c where c.hacker_id!=h.hacker_id
group by c.hacker_id
having cnt!= (select max(count(challenge_id)) from Challenges group by hacker_id))
order by total desc, h.hacker_id
Here is my MySql code and I got an error: ERROR 1111 (HY000) at line 1: Invalid use of group function.
I don't know what is wrong with this line: (select max(count(challenge_id)) from Challenges group by hacker_id)
How can I fix this error?
The link of the problem that I want to solve: https://www.hackerrank.com/challenges/challenges/problem
Upvotes: 1
Views: 250
Reputation: 1271151
The problem is the max(count(). However, I would solve it using
limit` rather than an additional subquery:
having cnt <> (select count(*)
from challenges
group by hacker_id
order by count(*) desc
limit 1
)
That said, this query is probably better written using window functions. However, without sample data, desired results, and a clear explanation of what the query should be doing, it is hard to make concrete suggestions.
Upvotes: 2
Reputation: 447
You can't have 2 grouping functions together with 1 group by.
Instead of
select max(count(challenge_id)) from Challenges group by hacker_id)
you can do
select max(cnt_challenge) from (select count(challenge_id) as cnt_challenge from Challenges group by hacker_id))
Upvotes: 4