1

我已经做了很多工作来得到我的结果,现在我被卡住了。我很难在网上找到这样的案例。

我有一张基本上像这样的桌子:

Name   |  Results
John   |  Win
John   |  Loss
John   |  Tie
Jim    |  Win
Jim    |  Win

这个表是从不同的游戏中衍生出来的,所以每一行本质上代表了一个游戏的玩家结果,每场游戏应该有两行,因为每场游戏有 2 个玩家。

无论如何,我想得到一些这样的结果,并且我已经尝试了各种奇怪的计数,但我很难获得一个具有正确计数的独特名称。这是我想要的:

NAME   | games_won   |  games_lost   |  games_tied
John   |      1      |       1       |       1
Jim    |      2      |       0       |       0

附带说明一下,这是我为获取第一个表而想出的令人难以置信的凌乱 SQL 语句,但我目前还拥有它,它还提供了这样的游戏 ID:

name  |  game_id  | result

如果您想开怀大笑,请仅在此处阅读,我 99% 确信有一种更简单的方法可以做到这一点,但请记住,我在这里的问题不是关于如何改进我在下面写的内容,这只是关于如何处理结果:

SELECT name, game_id,
    case
        when p1_score>p2_score then 'win'
        when p1_score<p2_score then 'loss'
        else 'tie'
    end as result
from player 
Inner JOIN game on player.player_id = game.p1_id

union select * from (SELECT name, game_id,
    case
        when p1_score>p2_score then 'win'
        when p1_score<p2_score then 'loss'
        else 'tie'
    end as result
from player 
Inner JOIN game on player.player_id = game.p2_id) as ta
4

1 回答 1

3
SELECT p.name,
    sum(case when p.player_id = g.p1_id and g.p1_score>g.p2_score
         or p.player_id = g.p2_id and g.p1_score<g.p2_score then 1 else 0 end) games_won,
    sum(case when p.player_id = g.p1_id and g.p1_score<g.p2_score
         or p.player_id = g.p2_id and g.p1_score>g.p2_score then 1 else 0 end) games_lost,
    sum(case when g.p1_score=g.p2_score then 1 else 0 end) games_tied
from player p
inner JOIN game g on p.player_id in (g.p1_id, g.p2_id)
group by p.name
于 2012-12-05T00:49:17.980 回答