创建一个mySQL查询来计算包含每个游戏结果的表中的胜负,我遇到了一些麻烦。该表看起来像:
Season | winning_team | losing_team | winning_points | losing_points
2003 1101 1102 65 45
2003 1104 1101 72 70
2004 1102 1103 88 63
我希望得到一些看起来像的东西:
Season | team | wins | losses
2003 1101 22 4
2004 1101 12 16
2003 1102 14 14
我真的不知道该怎么办。我可以得到刚刚获胜或只是失败的查询结果,但我似乎无法做到这两点。第一个查询获得获胜次数:
SELECT Season, winning_team, COUNT(winning_points) as wins
FROM cbb.regular_season
GROUP BY Season, winning_team
返回(示例):
Season | winning_team | wins
2003 1101 22
2004 1101 12
2003 1102 14
这第二次失败了:
SELECT Season, losing_team, COUNT(losing_points) as losses
FROM cbb.regular_season
GROUP BY Season, losing_team
返回(示例):
Season | losing_team | losses
2003 1101 3
2004 1101 16
2003 1102 14
我想将它们组合在一起,这样我就可以得到每个赛季的赛季,球队以及每个赛季的输赢数。
答案 0 :(得分:0)
select
season, team,
count(case when outcome = 'W' then 1 else null end) as wins,
count(case when outcome = 'L' then 1 else null end) as losses
from
(
select season, winning_team as team, 'W' as outcome from cbb.regular_season union all
select season, losing_team as team, 'L' as outcome from cbb.regular_season
) as games
group by season, team
答案 1 :(得分:0)
你有正确的中间步骤。现在你需要将它们组合在一起:
SELECT wins.Season
, wins.team
, wins.wins
, loses.loses
FROM (
SELECT Season
, winning_team as team
, COUNT(1) as wins
FROM cbb.regular_season
GROUP BY Season, winning_team
) as wins
, (
SELECT Season
, losing_team
, COUNT(1) as losses
FROM cbb.regular_season
GROUP BY Season, losing_team
) as loses
WHERE wins.Season = loses.Season
AND wins.team = loses.team
我没有尝试过,但它应该有效
正如评论中所提到的,如果一支球队只输了或只赢了,这将无效。