2014-02-06 59 views
0

我有2個由此的查詢,我試圖顯示0值。多個GROUP BY + COUNT在同一個表上顯示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

嘗試的WHERE子句中添加'%',像這樣: 'WHERE LIKE 「%活性%」' –

+0

狀態,這不是問題,它在沒有'%'的情況下運行良好 – dbaq

+0

COUNT(*)'永遠不能爲'0'。你有一組1+行或者你沒有組。顯示錶格和預期結果的一些示例數據,否則不容易看到您要做什麼。 –

回答

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; 
+0

在這種情況下,我也可以在我的結果PLAN = null。所以我需要使用'where'子句 – dbaq