SQL查询,根据相同的ID计算两列

时间:2014-09-23 21:44:51

标签: sql sql-server select join

我有两个表,团队和游戏的sql server数据库。每个游戏都有一个predict_winner列和一个获胜者列。两列都引用了team table 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

3 个答案:

答案 0 :(得分:1)

由于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

答案 1 :(得分: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 :(得分:0)

试试这个:

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