Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude MySQL result rows where count is zero

I have the following SQL query:

SELECT 
    COUNT(CASE WHEN u.account_new = 1 THEN u.user_id END) AS new_user, 
    COUNT(u.user_id) AS all_users, 
    c.country_name AS country 
FROM users u, countries c 
WHERE u.country_id = c.country_id 
GROUP BY u.country 

This shows a count of new users and total users grouped by country. I'd like to exclude rows where the count of new users is zero, but I'm not sure how to do this in the above SQL. At the moment I'm skipping them in PHP but thought there might be a better way to write the query.

Any suggestions are welcome.

like image 767
tamewhale Avatar asked Dec 13 '22 09:12

tamewhale


1 Answers

Use this: (note the HAVING clause)

SELECT 
    COUNT(CASE WHEN u.account_new = 1 THEN u.user_id END) AS new_user, 
    COUNT(u.user_id) AS all_users, 
    c.country_name AS country 
FROM users u, countries c 
WHERE u.country_id = c.country_id 
GROUP BY u.country 
HAVING COUNT(CASE WHEN u.account_new = 1 THEN u.user_id END) > 0
like image 134
Saket Avatar answered Dec 30 '22 00:12

Saket