我已经做了很多工作,我的结果到了这一点,现在我被卡住了。我很难在网上找到这样的案例。
我有一张基本上像这样的表:
Name | Results
John | Win
John | Loss
John | Tie
Jim | Win
Jim | Win
此表源自不同的游戏,因此每一行基本上代表游戏的玩家结果,每个游戏应该有两行,因为每个游戏有2个玩家。
无论如何,我想得到一些像这样的结果,我已经尝试了各种奇怪的东西与Counts,但我很难得到一个具有正确计数的独特名称。这就是我想要的:
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
答案 0 :(得分: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