【问题标题】:Join three tables for different Count加入三个不同计数的表
【发布时间】:2015-08-19 05:08:39
【问题描述】:

我有 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 来计算的。

【问题讨论】:

  • 你怎么知道drawcolumn Match_WonBy的值是多少
  • 根据您给我们的架构,没有TeamName 列。此外,您应该使用您正在使用的 SQL 类型来标记问题。
  • @Praveen : 对于 draw 值是 0.. 所以它是一个平局。
  • @TimBiegeleisen :TeamName 是 Team.. 刚刚复制粘贴查询表单我的 sql。

标签: sql join count


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

【讨论】:

  • 兄弟,非常感谢。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 1970-01-01
  • 2021-07-19
  • 2015-11-22
  • 2021-05-27
  • 1970-01-01
  • 2018-12-11
相关资源
最近更新 更多