为不同的Count加入三个表

时间:2015-08-19 05:08:39

标签: sql join count

我有3张桌子。

   TeamId        Team 
    1       Manchester United
    2       Arsenal 
    3       Liverpool

匹配

 MatchId HomeTeamId AwayTeamId  MatchStartDate Match_WonBy
  3         1           2          2/2/2015       2
  8         3           1          6/2/2015       3

得分

  ScoreId MatchId TeamId      ScorTime
  1         3      1      2/2/2015 12:30:00
  2         3      2      2/2/2015 12:35:00
  3         3      1      2/2/2015 12:38:00
  4         8      1      6/2/2015 12:45:00
  5         8      1      6/2/2015 12:49:00

我试过这个,但我没弄明白。

SELECT Team.TeamName, COUNT(h.HomeTeamId) AS TotalMatch,
    SUM(CASE WHEN h.Match_Status = Team.TeamId THEN 1 ELSE 0 END) AS HomeScore,
    SUM(CASE WHEN h.Match_WonBy  = Team.TeamId OR a.Match_Status= Team.TeamId THEN 1 ELSE 0 END) AS Total
FROM Team RIGHT JOIN Match h
ON Team.TeamId = h.HomeTeamId JOIN Match a
ON Team.TeamId = a.AwayTeamId  
GROUP BY Team.TeamName

我需要这个我没有得到的。enter image description here

仅供参考:它不是作业。

这里的积分是通过将3乘以胜利并将1加到平局来计算的。

1 个答案:

答案 0 :(得分:1)

试试这个:

select 
    t.Team,
    count(x.TeamId) played,
    sum(coalesce(x.win, 0)) as win,
    sum(coalesce(x.loss, 0)) as loss,
    count(x.TeamId) - sum(coalesce(x.win, 0)) - sum(coalesce(x.loss, 0)) as draw, 
    sum(coalesce(x.win, 0)) * 3 + (count(x.TeamId) - sum(coalesce(x.win, 0)) - sum(coalesce(x.loss, 0))) as point
from Team t
left join (
    select 
    HomeTeamId TeamId,
    case when Match_WonBy = HomeTeamId then 1 else 0 end win,
    case when Match_WonBy = AwayTeamId then 1 else 0 end loss
    from Match
    union all
    select
    AwayTeamId TeamId,
    case when Match_WonBy = AwayTeamId then 1 else 0 end win,
    case when Match_WonBy = HomeTeamId then 1 else 0 end loss
    from Match
) x on t.TeamId = x.TeamId
group by t.Team
order by
sum(coalesce(x.win, 0)) * 3 + (count(x.TeamId) - sum(coalesce(x.win, 0)) - sum(coalesce(x.loss, 0))) desc