简体   繁体   中英

Invalid use of GROUP BY operator after WHERE clause

The following query successfully returns the specific users (by id) who have printed the most:

SELECT file_prints.user_id, user.major, sum(print_pages) FROM `file_prints`
INNER JOIN `user` on file_prints.user_id = user.user_id GROUP BY
file_prints.user_id 
ORDER BY sum(print_pages)

When I introduce a where clause to try to eliminate the users who have not printed at all (that is to say, where sum(print_pages) == 0), I write the following query:

SELECT file_prints.user_id, user.major, sum(print_pages) FROM `file_prints`
INNER JOIN `user` on file_prints.user_id = user.user_id WHERE
sum(print_pages) > 0 GROUP BY file_prints.user_id 
ORDER BY sum(print_pages)

and get the following error:

 #1111 - Invalid use of group function 

How do I eliminate the results which have 0 for sum(print_pages)?

This is because you can't use a aggregate function with WHERE clause. So, use HAVING clause like this:

SELECT file_prints.user_id, user.major, sum(print_pages) 
FROM `file_prints`
INNER JOIN `user` on file_prints.user_id = user.user_id
GROUP BY file_prints.user_id
HAVING sum(print_pages) > 0 
ORDER BY sum(print_pages)

You need to use the having keyword instead as you are working on an aggregate:

SELECT file_prints.user_id, user.major, sum(print_pages) FROM `file_prints`
INNER JOIN `user` on file_prints.user_id = user.user_id 
GROUP BY file_prints.user_id 
HAVING sum(print_pages) > 0 
ORDER BY sum(print_pages)

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