0

我正在努力确定我正在尝试编写的 SQL Server 2012 查询,并希望有人能帮助我。这是我目前的查询:

 --home wins
 select NULL as roadlosses, Count(t1.TeamName) as homewins, t1.TeamName from scores s
 inner join games g
 on g.GameID=s.GameID
 inner join teams t1
 on t1.TeamID=g.HomeTeam
 inner join teams t2
 on t2.Teamid=g.AwayTeam
 where (s.hometotalruns - s.awaytotalruns) > 0 and t1.TeamName = 'Pirates'
 group by t1.teamname

 UNION
 --road losses

 select Count(t2.TeamName) as roadlosses, NULL, t2.TeamName from scores s
 inner join games g
 on g.GameID=s.GameID
 inner join teams t1
 on t1.TeamID=g.HomeTeam
 inner join teams t2
 on t2.Teamid=g.AwayTeam
 where (s.hometotalruns - s.awaytotalruns) > 0 and t2.TeamName = 'Pirates' 
 group by t2.TeamName

这让我很接近,结果是:

 roadlosses    homewins     teamname
 NULL            41          Pirates
 26             NULL         Pirates

我希望它只返回 1 行,消除NULLs,但我似乎无法得到它。

我试着看看这个,但这并不完全是我所需要的。

4

2 回答 2

2

由于您知道您所追求的团队名称,我认为将其拉出而不是在整个查询中连续引用它是有意义的,并且根本不必在主查询中加入到团队表中。如果团队名称是唯一的(我当然希望如此!),这应该是一个非常便宜的搜索。

-- this would be your input parameter:
DECLARE @TeamName VARCHAR(32) = 'Pirates';

-- the rest would be the code:
DECLARE @TeamID INT;
SELECT @TeamID = TeamID FROM dbo.Teams WHERE TeamName = @TeamName;

;WITH x AS 
(
   SELECT 
     location = CASE g.HomeTeam WHEN @TeamID THEN 'H' ELSE 'A' END,
     run_diff = s.hometotalruns - s.awaytotalruns
   FROM dbo.Scores AS s
   INNER JOIN dbo.Games AS g
   ON s.GameID = g.GameID
   WHERE @TeamID IN (g.HomeTeam, g.AwayTeam)
)
SELECT 
 RoadLosses = COUNT(CASE WHEN location = 'A' AND run_diff > 0 THEN 1 END),
 HomeWins   = COUNT(CASE WHEN location = 'H' AND run_diff > 0 THEN 1 END),
 TeamName   = @TeamName  
FROM x;
于 2013-08-13T03:25:17.477 回答
1

将此作为单个查询执行,并带有条件聚合。我认为这是查询:

 select sum(case when (s.hometotalruns - s.awaytotalruns) > 0 and t2.TeamName = 'Pirates' 
                 then 1 else 0
            end) as roadlosses,
        sum(case when (s.hometotalruns - s.awaytotalruns) > 0 and t1.TeamName = 'Pirates'
                 then 1 else 0
            end) as homewins,
        'Pirates' as TeamName
 from scores s
 inner join games g
 on g.GameID=s.GameID
 inner join teams t1
 on t1.TeamID=g.HomeTeam
 inner join teams t2
 on t2.Teamid=g.AwayTeam
 where 'Pirates' in (t1.TeamName, t2.teamName);
于 2013-08-13T03:15:38.817 回答