sql - 如何根据此 SQL 表计算总输赢
问题描述
我有一个名为 games(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
试过这个,但不能让它做我想做的事。谢谢!
解决方案
反透视数据并聚合:
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;
推荐阅读
- linq - EF Core 中孙子属性的 Include 与 ThenInclude
- asp.net - 如何从 json 字符串 asp.net mvc Newtonsoft.json 获取对象列表
- sql - 如何在 Coldfusion SQL 查询中处理 Ä Ö Ü 之类的变音符号以插入数据库?
- url - 谷歌分析所有数据视图中的 URI 之后的 URL 记录?
- .net - 如何在文本框(ASP.NET MVC)前面添加美元符号
- javascript - Gatling 不会保存访问令牌
- reactjs - 重定向而不更改 url
- python - 多个熊猫数据帧的时间排序?
- powershell - PowerShell 不会遍历文档
- python-3.x - 如何手动进行 pip 安装