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开发者_StackOverflow社区. 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
This includes a better reading improvement for counting new users:
SELECT
SUM(u.account_new=1) 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 SUM(u.account_new=1)>0
精彩评论