在同一行中结合赢利和亏损

时间:2013-08-13 03:03:45

标签: sql sql-server tsql sql-server-2012

我正在努力确定我正在尝试编写的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行,取消NULL s,但我似乎无法得到它。

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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);