2014-05-03 53 views
0

我想按類別顯示在數據庫記錄和計數狀態的狀態,顯示記錄的種類和數量與總

假設我在數據庫中的這些記錄,

agent_tbl

========================= 
    | directors || status | 
    ========================= 
    |  AAA || Suspended | 
    |  BBB || Deleted | 
    |  CCC || Active | 
    |  AAA || Deleted | 

這是我想要獲取的結果:

Directors | Active | Suspended | Deleted | 
------------------------------------------ 
AAA  | 0 |  1 | 1 | 
------------------------------------------ 
BBB  | 0 |  0 | 1 | 
------------------------------------------ 
CCC  | 1 |  0 | 0 | 
------------------------------------------ 
Total   1   1   2 | 
------------------------------------------ 

這裏是我的闕RY

SELECT director,COUNT(*) 
FROM agent_tbl   
GROUP BY director; 
+0

你可能想開始接受幫助你的答案。 –

回答

0
--For each director 
select directors, 
count(case when status = 'Active' then 1 else null end) as 'Active', 
count(case when status = 'Suspended' then 1 else null end) as 'Suspended', 
count(case when status = 'Deleted' then 1 else null end) as 'Deleted' 
from agent_tbl 
group by directors 
union 
--Hard code for the total row 
select 'Total', 
count(case when status = 'Active' then 1 else null end) as 'Active', 
count(case when status = 'Suspended' then 1 else null end) as 'Suspended', 
count(case when status = 'Deleted' then 1 else null end) as 'Deleted' 
from agent_tbl 

演示here

+0

hi @ shree.pat18讚賞!奇蹟般有效。 :) –

+0

你知道如何接受作品?還有其他問題,你也添加了相同的評論來表示讚賞,但沒有接受答案。 http://stackoverflow.com/help/accepted-answer http://stackoverflow.com/help/someone-answers –

+0

嗨@ shree.pat18對不起我初學者,我需要做什麼?接受按鈕? –

0
SELECT Directors, 
     SUM(status = 'Active') AS Active, 
     SUM(status = 'Suspended') AS Suspended, 
     SUM(status = 'Deleted') AS Deleted 
FROM agent_tbl 
GROUP BY Directors