2014-01-16 113 views
1

我有兩個表(讓我們稱之爲他們的情況和用戶)的結構是這樣的:案例mysql的SELECT和COUNT WHERE

ID|status  |user_id 
__|____________|_______ 
1 |Open  |6 
2 |Closed  |9 
3 |Incomplete |9 

用戶:

ID| 
__|_____ 
6| 
9| 

我想選擇一個計數該ID以及每個狀態字段的計數。

目前我曾嘗試:

SELECT COUNT(c.id), COUNT(
(SELECT status from cases where status = 'Open')), 
COUNT(
(SELECT status from cases where status = 'Closed')), 
COUNT(
(SELECT status from cases where status = 'Incomplete')) 
FROM cases as c 
JOIN users as u on u.id = c.user_id 

我正在查詢的錯誤返回多行。

這就是我想實現

ID| Open | Closed | Incomplete |user_id 
__|______|________|____________|__________ 
2|0  |1  |1   |9 

回顧:一種計數多少ID的每個用戶ID數,併爲每個狀態的計數。

回答

3

您可以sum

SELECT COUNT(c.id), 
SUM(c.status = 'Open') Open , 
SUM(c.status = 'Closed') Closed , 
SUM(c.status = 'Incomplete') Incomplete, 
u.id user_id 
FROM cases as c 
JOIN users as u on u.id = c.user_id 
GROUP BY u.id 
+1

這看起來是一個合理的答案試試這個。這真的很難說是否真的回答了這個問題。 –

+1

德普時刻。謝謝! – Kisaragi