基于同一表中的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等优化任何建议此查询将是有益的。
谢谢。
答
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
真正的杰作,它工作得更好,然后我期望。谢谢。 – Alexander 2011-05-06 13:00:10