我有兩個表,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」和其他像紅色,綠色和藍色等數字不匹配。 我不知道是否有可能得到我想要的結果。