【问题标题】:How to calculate total wins and losses based on this SQL Table如何根据此 SQL 表计算总输赢
【发布时间】:2019-10-19 16:31:26
【问题描述】:

我有一个名为 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

试过这个,但不能让它做我想做的事。谢谢!

【问题讨论】:

    标签: sql


    【解决方案1】:

    加入表格并使用条件聚合:

    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

    【讨论】:

      【解决方案2】:

      反透视数据并聚合:

      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;
      

      【讨论】:

      • 我在任何地方都没有看到“团队”的定义。
      • @donPable 。 . .我修正了错字。那应该是team_id
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多