我有以下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
显示按国家/地区分组的新用户和总用户数。我想排除新用户数为零的行,但我不确定如何在上面的SQL中执行此操作。目前我正在使用PHP跳过它们,但认为可能有更好的方法来编写查询。
欢迎任何建议。
答案 0 :(得分:9)
使用此: (注意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
答案 1 :(得分:3)
这包括为计算新用户提供更好的阅读改进:
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