根据同一个表中的2个不同值获取计数

时间:2011-05-06 12:44:33

标签: sql

我正在尝试向用户提取游戏应用程序的统计信息,但需要帮助才能使其无需进行多个查询。

简而言之,就是这样: 表:userid(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之后计算它们,但是当数据库中存在大量游戏时,这种方法非常慢。

所以我基本上想要一个按种族分组的查询:

比赛|赢|损失

A_的 _ ___ X _ ___ _x

B_的 _ ___ X _ ___ _x

C_的 _ ___ X _ ___ _x

我对更复杂的SQL形式很陌生,因此任何有关优化此查询的建议都会有所帮助。

谢谢。

1 个答案:

答案 0 :(得分: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