0

我需要你的帮助:

我为用户、游戏和结果设置了一组关系表,我正在尝试计算每个用户的获胜百分比。

感谢大量浏览,我发现了以下方法:

SELECT Winner, (COUNT(Winner) * games.TotalPlayed) AS PercentWon
FROM Results
JOIN (
  SELECT 100/COUNT(*) AS TotalPlayed
  FROM games
  where Player_1 = 'John' OR Player_2 = 'John'
) AS games

where Winner == 'John' 
GROUP BY Winner
ORDER BY PercentWon DESC;

这对于获取 Johns % 非常有效,但我希望它扫描整个结果表并为每个人打印值。但是,我不允许使用:

SELECT Winner, (COUNT(Winner) * games.TotalPlayed) AS PercentWon
FROM Results
JOIN (
  SELECT 100/COUNT(*) AS TotalPlayed
  FROM games
  where Player_1 = Winner OR Player_2 = Winner
) AS games

where Winner != 'Draw' 
GROUP BY Winner
ORDER BY PercentWon DESC;

因为没有定义获胜者。如何在执行子查询时将获胜者的值传递给子查询?

4

1 回答 1

0

我终于想出了一些对你有用的东西。这很棘手,因为玩家可以在games表中的两个字段之一中。

SELECT player, (COALESCE(totalWon, 0) / count(*) * 100) as PercentWon
FROM ((SELECT DISTINCT Player_1 as player FROM games) UNION (SELECT DISTINCT Player_2 as player FROM games)) players
INNER JOIN games on (games.Player_1 = player or games.Player_2=player)
LEFT JOIN
(
    SELECT Winner, COUNT(Winner) as totalWon
    FROM Results
    WHERE Winner != 'Draw' 
    GROUP BY Winner
) as winners
ON winners.Winner = player
GROUP BY player
ORDER BY PercentWon DESC;

FROM 子句中的 UNION 正在构建一个用户列表,我可以使用它来加入游戏(查找每位玩家的游戏总数)和获胜者(查找每位玩家的获胜次数)。

COALESCE 用于玩家没有赢得任何比赛的情况。由于我们正在加入表,这允许我们在没有匹配项时默认为 0 而不是 NULL。

这是基于我对您的架构的假设的 sqlfiddle:

http://sqlfiddle.com/#!2/d762c/1/0

于 2013-04-03T14:56:08.827 回答