2017-05-09 83 views
0

我有兩個表,id是連接它們的關鍵。在一個表中有重複的ID,狀態欄是枚舉類型。另一個也有ID,但它是獨一無二的,並且有像加入日期那樣的列。我必須知道每月和每年加入多少用戶,所以我必須按年份和月份進行分組。這是我所做的查詢。mysql:做條件不同的情況下

SELECT year(member.joined) AS year, 
     month(member.joined) AS month, 
     count(DISTINCT member.id) AS count 
FROM member 
WHERE member.id NOT IN 
(SELECT internal.worker_id FROM internal) 
GROUP BY year(member.joined), month(member.joined); 

這就給了我這樣的結果。

year  month   count 
1982   12   43   
1978   11    1 

但是,我也必須弄清楚用戶種類的數量,這是我想得到的結果。

year  month   count  red green blue 
1982  12    43   1 40  2 
1978  11    1   0  1  0 

所以我試圖通過添加具有類似這樣的類型的枚舉列的名稱來編輯查詢。

count(DISTINCT member.id) AS count, 
count(case c.`types` when 'red' then 1 else 0 end)as 'red', 
count(case c.`types` when 'green' then 1 else 0 end)as 'green', 
count(case c.`types` when 'blue' then 1 else 0 end)as 'blue' 

我收到了一條錯誤消息,說明mysql語法不正確。我試過這個查詢沒有做count(distint member.id)AS計數,它工作。然而,結果只是顯示了一切而沒有刪除重複項,所以「count」和其他像紅色,綠色和藍色等數字不匹配。 我不知道是否有可能得到我想要的結果。

回答

0

您是否嘗試過(CASE WHEN c.types='red' THEN 1 ELSE 0 END)語法?這是the docs中列出的第二個版本。另外,確切的查詢和錯誤信息會有幫助 - 例如,表'c'是什麼?這裏有加入嗎?

0

嘗試以下查詢:

SELECT year(member.joined) AS year, 
     month(member.joined) AS month, 
     count(DISTINCT member.id) AS count, 
     sum(if(member.`types` like 'red', 1, 0)) as 'red', 
     sum(if(member.`types` like 'green', 1, 0))as 'green', 
     sum(if(member.types like 'blue', 1, 0))as 'blue' 
FROM member 
GROUP BY year(member.joined), month(member.joined); 

當使用GROUP BY在這種情況下,最好是使用金額,如果()子句