我有一个像这样的桌子“游戏”
| team1_id | team2_id | team1_pts | team2_pts |
1 3 101 117
2 5 99 98
我要选择从表“ team”中退回球队名称并像这样的赢/输记录
| team_name | win | loss
Boston 15 11
Miami 13 12
我想出了如何只获得获胜次数的表,却不知道如何在同一张表中获得胜负。
答案 0 :(得分:1)
您可以取消透视并重新加入:
select t.name, sum(is_win) as num_wins, sum(is_loss) as num_losses
from ((select (case when team1_pts > team2_pts then team1_id else team2_id end) as team_id,
1 as is_win, 0 as is_loss
from game g
) union all
(select (case when team1_pts < team2_pts then team1_id else team2_id end) as team_id,
0, 1
from game g
)
) g join
teams t
on t.team_id = g.team_id
group by t.name
答案 1 :(得分:0)
我认为您应该重新访问数据模型。也许GAMES
表具有字段GAME_ID, TEAM_ID, POINTS
。您可能可以使它与目前的功能一起使用,但并不理想。
答案 2 :(得分:0)
这可以做到:
select team_id ,
sum(case when Points > 0 then 1 else 0 end) as Win,
sum(case when Points < 0 then 1 else 0 end) as Loss
from
(
select team1_id as team_id , team1_pts - team2_pts as Points from games
union all
select team2_id, team2_pts - team1_pts as Points from games
)tbl
group by team_id