2011-06-04 99 views
0

我有以下模式的日誌表:MySQL查詢幫助

OperatorId - JobId - Status (Good/Bad/Ugly) 
Alex   6  Good 
Alex   7  Good 
James  6  Bad 

說明:當操作員工作在一個工作,一個條目與狀態一起做。而已。

現在我需要像一個報告:

OperatorId - Good Count - Bad Count - Ugly Count 
Alex   2   0   0 
James  0   1   0 

幫助!

回答

2
select operatorid, 
sum(if(status="good",1,0)) as good, 
sum(if(status="bad",1,0)) as bad, 
sum(if(status="ugly",1,0)) as ugly 
from table 
group by operatorid 
+1

更簡潔比我的! – 2011-06-04 20:16:12

+0

aww ... sum在mysql中也是這樣工作的呢?我認爲它只能在這樣的SQL服務器上工作。無論如何,感謝您發佈解決方案! – effkay 2011-06-04 20:20:06

+0

其實我也認爲總和,如果語法是特定於SQL Server。從未在MySQL中嘗試過。 – 2011-06-04 20:25:25

1

這被稱爲數據透視表。它通過設定各狀態的值1或0,然後總結起來做:

SELECT 
    T.OperatorId, 
    SUM(T.GoodStat) AS Good, 
    SUM(T.BadStat) AS Bad, 
    SUM(T.UglyStat) AS Ugly 
FROM 
(
SELECT 
    CASE WHEN Status = 'Good' THEN 1 ELSE 0 END AS GoodStat, 
    CASE WHEN Status = 'Bad' THEN 1 ELSE 0 END AS BadStat, 
    CASE WHEN Status = 'Ugly' THEN 1 ELSE 0 END AS UglyStat, 
    OperatorId 
    FROM logTable T 
) 
GROUP BY T.OperatorId 
1

如果像我一樣,你喜歡,只要有可能,計算與計數時,而不是SUM,這裏是一個替代解決方案,它使用this thread詢問的方法:

SELECT 
    operatorid, 
    COUNT(status = 'good' OR NULL) as good, 
    COUNT(status = 'bad' OR NULL) as bad, 
    COUNT(status = 'ugly' OR NULL) as ugly 
FROM table 
GROUP BY operatorid