[英]Exclude MySQL result rows where count is zero
I have the following SQL query: 我有以下SQL查询:
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.
我想排除新用户数为零的行,但我不确定如何在上面的SQL中执行此操作。 At the moment I'm skipping them in PHP but thought there might be a better way to write the query.
目前我正在用PHP跳过它们,但认为可能有更好的方法来编写查询。
Any suggestions are welcome. 欢迎任何建议。
Use this: (note the HAVING clause) 使用此:(注意HAVING子句)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.