【问题标题】:How to select win/loss record in mysql如何在mysql中选择赢/输记录
【发布时间】:2019-12-27 23:56:21
【问题描述】:

我有看起来像这样的桌面“游戏”

| team1_id | team2_id | team1_pts | team2_pts |

     1          3        101        117

     2          5        99         98

我想做选择,从表“团队”中返回团队名称和这样的赢/输记录

| team_name | win | loss 

   Boston     15   11        

   Miami      13   12       

我想出了如何获得只有获胜次数的桌子,但不知道如何在同一张桌子上获得胜利和失败。

【问题讨论】:

    标签: mysql sql


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      我认为您应该重新审视您的数据模型。也许GAMES 表有字段GAME_ID, TEAM_ID, POINTS。你可能可以让它与你目前所拥有的一起工作,但它并不理想。

      【讨论】:

      • 这应该是评论,而不是答案。
      【解决方案3】:

      这样就可以了:

      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 
      

      【讨论】:

        猜你喜欢
        • 2012-06-04
        • 1970-01-01
        • 2011-04-11
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 2011-02-12
        • 2011-09-25
        • 1970-01-01
        相关资源
        最近更新 更多