【问题标题】:SQL Query, Count two columns based on same idSQL查询,根据相同的id计算两列
【发布时间】:2023-03-08 00:51:01
【问题描述】:

我有两个表、团队和游戏的 sql server 数据库。每场比赛都有一个predicted_winner 列和一个winner 列。两列都引用了团队表 id 字段。我想查询数据库并计算球队预计会赢多少场比赛,以及他们实际赢了多少场比赛。但是,根据我的查询,它只返回 predict_winner 或获胜者的计数,无论我加入团队表的哪一列。如何获得两列的准确计数。

这是我的错误查询

SELECT teams.id, count(predicted_Winner), count(winner)
FROM teams left join games on teams.id=games.predicted_winner
GROUP BY teams.id

【问题讨论】:

  • 为我们提供输入/输出,最好有sqlfiddle 链接

标签: sql sql-server select join


【解决方案1】:

加入表格两次,每列一次:

SELECT    teams.id, COUNT(pw.predicted_winner), COUNT(w.winner)
FROM      teams 
LEFT JOIN games pw ON teams.id = pw.predicted_winner
LEFT JOIN games w ON teams.id = w.winner
GROUP BY  teams.id

【讨论】:

    【解决方案2】:

    由于games 表中有两列引用回Teams 表中的一列,

    您需要将此表连接回Teams 表两次,每列引用teams 表一次。

    SELECT t.id
         , count(g1.predicted_Winner) AS predicted_Winner_count
         , count(g2.winner)           AS winner_count
    FROM teams t
    LEFT JOIN games g1 on t.id = g1.predicted_winner
    LEFT JOIN games g2 on t.id = g2.winner
    GROUP BY t.id
    

    【讨论】:

      【解决方案3】:

      试试这个:

      with results(game_id, predicted_Winner, winner) as (
        select 1, 1, 2  union all 
        select 2, 1, 2  union all 
        select 3, 1, 1  union all 
        select 4, 4, 4  union all 
        select 5, 5, 6  union all 
        select 6, 6, 6  union all 
        select 7, 3, 5  
      ), teams(id) as (
        select 1  union all 
        select 2  union all
        select 3  union all 
        select 4  union all 
        select 5  union all 
        select 6 
      )
      SELECT t.id team_id
           , count(case when predicted_winner = t.id then 1 end)
           , count(case when predicted_winner = t.id and predicted_winner = winner then 1 end)
        from results res
        right join teams t on t.id = res.predicted_winner or t.id = winner
       group by t.id
       order by 1
      

      SQLFiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-24
        • 2016-08-25
        • 2015-04-27
        • 1970-01-01
        • 2019-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多