加入三个表以获取不同的计数

Join three tables for different 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

我需要这个,但我没有得到。

仅供参考:这不是作业。

这里的分数是赢的乘以3,平的加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