2011-05-06 165 views
2

我試圖向用戶提取遊戲應用程序的統計信息,但需要幫助使其與使用多於一個查詢的工作無關。基於同一表中的2個不同值獲取計數

這是它的外觀在很短的瞬間:用戶ID(X INT),結果(勝和損失),種族(A,B和C)

我現在需要獲取計數: 表贏和損失每個種族:

Select count(outcome) as win from games where userid = X and outcome = 'win' AND race = A 

Select count(outcome) as loss from games where userid = X and outcome = 'loss' AND race = A 

Select count(outcome) as win from games where userid = X and outcome = 'win' AND race = B 

Select count(outcome) as loss from games where userid = X and outcome = 'loss' AND race = B 

Select count(outcome) as win from games where userid = X and outcome = 'win' AND race = C 

Select count(outcome) as loss from games where userid = X and outcome = 'loss' AND race = C 

然後我基本上計算它們在PHP之後,但這是可笑緩慢的方式,當大量的遊戲是在數據庫中。

所以我基本上想有一個查詢組種族是這樣的:

賽| Win |損失

A_ _ ___X_ ___ _x

B_ _ ___X_ ___ _x

C_ _ ___X_ ___ _x

我是很新的更復雜的形式的SQL等優化任何建議此查詢將是有益的。

謝謝。

回答

3
SELECT race, 
     COUNT(CASE 
       WHEN outcome = 'win' THEN 1 
      END) AS win, 
     COUNT(CASE 
       WHEN outcome = 'loss' THEN 1 
      END) AS loss 
FROM games 
WHERE userid = X 
     AND race IN ('A', 'B', 'C') 
GROUP BY race 
+0

真正的傑作,它工作得更好,然後我期望。謝謝。 – Alexander 2011-05-06 13:00:10

相關問題