我有一个称为游戏的表(game_id,home_id,home_score,away_id,away_score,date)和一个名为team(team_id,team_name)的表。我需要一个SQL查询来基于home_score和away_score计算每个团队的总得失和获胜百分比(胜出/比赛数)记录。
select game_id, home_score, away_score, case when home_score > away_score then 'true' else 'false ' end from game_schedule
尝试过此操作,但无法执行我想要的操作。谢谢!
答案 0 :(得分:0)
取消数据透视并聚合:
select team_id, sum(is_win) as num_wins, sum(is_loss) as num_losses,
avg(is_win) as win_ratio
from ((select home_id as team_id,
(case when home_score > away_score then 1 else 0 end) as is_win,
(case when home_score < away_score then 1 else 0 end) as is_loss
from games
) union all
(select away_id,
(case when away_score > home_score then 1 else 0 end) as is_win,
(case when away_score < home_score then 1 else 0 end) as is_loss
from games
)
) g
group by team_id;
答案 1 :(得分:0)
加入表并使用条件聚合:
select tt.team_id, tt.team_name,
sum(case when result > 0 then 1 else 0 end) totalwin,
sum(case when result < 0 then 1 else 0 end) totalloss,
100.0 * avg(case when result > 0 then 1 else 0 end) percentwin
from (
select t.team_id, t.team_name,
(g.home_score - g.away_score) * case
when t.team_id = g.home_id then 1
when t.team_id = g.away_id then -1
end result
from team t left join games g
on t.team_id in (g.home_id, g.away_id)
) tt
group by tt.team_id, tt.team_name
查看简化的demo。