简体   繁体   中英

MYSQL ERROR 1111 (HY000) at line 1: Invalid use of group function. How can I fix this error?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM