我有2个分组的查询,我试图显示0个值。
SELECT plan, locale, COUNT( * ) AS res
FROM domain
WHERE status LIKE "active"
AND plan IS NOT NULL
GROUP BY plan, locale
我知道我必须在同一张桌子上进行左连接,但我无法使其正常工作
SELECT d1.plan, d1.locale, IFNULL(COUNT(d2.id), 0) AS res
FROM domain AS d1
LEFT JOIN domain AS d2 ON d1.id = d2.id
WHERE d1.plan IS NOT NULL
GROUP BY d1.plan, d1.locale
我做错了什么?
感谢您的帮助。
答案 0 :(得分:0)
不要使用where
条款。使用条件聚合:
SELECT plan, locale,
sum(case when status LIKE 'active' AND plan IS NOT NULL then 1 else 0 end) as res
FROM domain
GROUP BY plan, locale;
编辑:
SELECT plan, locale,
sum(case when status LIKE 'active' then 1 else 0 end) as res
FROM domain
WHERE plan is not null
GROUP BY plan, locale;