2011-05-01 136 views
0

我目前的數據庫設置:MySQL查詢問題

Forename | Surname | Department | Completion_Status 
Tom  Smith  Sales  Started 
Bob  Jones  Sales  Completed 
Alison  Baines Sales  Not Started 
Arthur  Smith  Marketing Started 
Claire  Staines Marketing Completed 

我能夠返回的行總數沒有在那裏完成狀態被啓動或完成,但不是在一個單一的任何問題,並且總數聲明 - 不過,我想做些什麼,在單個語句,是:

COUNT for Department As Total AND the COUNT for Department As Responses WHERE Completion_Status IN ('Started', 'Completed') 

這將是這個樣子:

Department | Total | Responses 
Sales  3  2 
Marketing 2  2 

希望有道理!?

謝謝荷馬。

回答

0
select 
department, 
count(department) as total, 
sum(if(completion_status IN ('Started', 'Completed'),1,0)) as responses 
from table 
group by department 

這是一個比較標準版

select 
department, 
count(department) as total, 
sum(case when completion_status in ('Started', 'Completed') then 1 else 0 end) as responses 
from table 
group by department 
+0

好吧,響應 FROM tresults 似乎接近 - 返回正確的總數,但兩個響應都是1,這是不正確的。有什麼建議麼? – 2011-05-01 12:30:12

+0

我現在對它進行了測試,結果是正確的 – 2011-05-01 12:33:17

+0

重新檢查 - 爲Total返回正確的值,但def爲響應帶來了bck 1 - 這是不正確的:( – 2011-05-01 12:44:33

1

SELECT  部門,
              COUNT(DEPT)                            AS  總,
              COUNT(completion_status)  AS  響應
FROM       tresults
WHERE     completion_status   IN  (  '已啓動',  '已完成'  )
集團    BY  部門
ORDER     BY   DEP  

+0

你忘了在選擇列表中添加部門。 – 2011-05-01 12:26:11

+0

感謝您的反饋 - 可悲的是,這是行不通的。 – 2011-05-01 12:26:52

+0

..甚至從條款 – 2011-05-01 12:27:28