在SQL Server中遇到SUM问题

时间:2013-09-15 11:50:51

标签: sql-server select sum

我有三个表Match_EventTeam_DetailMatch_Schedule

Match_ScheduleMatchIdHometeam_IdAway TeamId

matchId  HTeam  Ateam
----------------------
  123     -1      -7 
  231     -3      -5

Match_event包含与该匹配相关的内容。 (监狱,犯规等)

matchId    TeamId    Score
--------------------------------
  123         1         1    
  123         1         1  
  123         7         1    
  231         5         1

最后一张桌子(TeamDetail

 TeamId    TeamName
   123     USA
   231     Uk

我试过这个

SELECT      
    Team_Detail.Team_Name,  
    SUM(CASE WHEN Team_Detail.Serno = Match_Events.Team_Id THEN 1 ELSE 0 END) AS HomeTeamScore, 
    Team_Detail.Team_Name, 
    SUM(CASE WHEN Team_Detail.Serno = Match_Events.Team_Id THEN 1 ELSE 0 END) AS AwayTeamScore              
FROM         
    Match_Schedule  
INNER JOIN 
    Match_Events ON Match_Schedule.Match_Serno = Match_Events.Match_ID   
INNER JOIN
    Team_Detail ON Match_Events.Team_Id = Team_Detail.Serno 
GROUP BY 
    Team_Name, Team_Name

我得到了正确的结果,但是一个在另一个之上,而不是在同一行。

有人可以帮助我。

由于

2 个答案:

答案 0 :(得分:0)

这里有一些缺失的信息 - 我在您的查询中看到您引用了名为 Serno 的列,但它们未在上面的表定义中指定。

在你的示例数据中看起来好像是混合了matchID和TeamID(我看到匹配和团队的ID都是123和231)。

我想你可能想要两次加入Team_Detail表。一旦表格被别名为HomeTeam(或类似的东西),并且只为主队加入Match_Schedule。

对于客场球队来说同样的事情。

这样的事情:

SELECT  HomeTeam.Team_Name AS HomeTeamName, AwayTeam.Team_Name AS AwayTeamName, 
        SUM(CASE WHEN HomeTeam.TeamID = Match_Events.TeamId THEN Score ELSE 0 END) AS HomeTeamScore,
        SUM(CASE WHEN AwayTeam.TeamID = Match_Events.TeamId THEN Score ELSE 0 END) AS AwayTeamScore
FROM    Match_Schedule
JOIN    Match_Events ON Match_Events.MatchID = Match_Schedule.MatchID
JOIN    Team_Detail AS HomeTeam ON HomeTeam.TeamID = Match_Schedule.HTeam
JOIN    Team_Detail AS AwayTeam ON AwayTeam.TeamID = Match_Schedule.ATeam
GROUP BY HomeTeam.Team_Name, AwayTeam.Team_Name  

另外,我认为你根据得分而不是一个硬编码的1值来进行补偿......除非球队的得分总是1(表示胜利,也许)。

答案 1 :(得分:0)

如果您希望单个匹配的信息在一行上,则应按MatchId进行汇总。然后使用条件聚合来获取您要查找的信息。

SELECT max(case when ms.hteam = td.TeamId then Team_Detail.Team_Name end) as hometeam,  
       SUM(CASE WHEN ms.hteam = td.TeamId THEN me.score ELSE 0 END) AS HomeTeamScore, 
       max(case when ms.ateam = td.TeamId then Team_Detail.Team_Name end) as awayteam, 
       SUM(CASE WHEN ms.hteam = td.TeamId THEN me.score ELSE 0 END) AS AwayTeamScore              
FROM Match_Schedule ms INNER JOIN 
     Match_Events me
     ON ms.matchId = me.matchID INNER JOIN
     Team_Detail td
     ON me.teamId = td.teamId 
GROUP BY ms.matchid;

注意其他一些事情。我更改了查询以根据问题中的描述使用字段,而不是查询中的示例。我还更新了计算以使用score字段,而不是仅计算1