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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With