如何在没有子查询的情况下对一个新表中的两个查询求和

时间:2019-06-05 21:51:10

标签: sql sql-server tsql sum subquery

我有两个查询,它们从两个不同的表中获取两个不同列的总和。我面临的问题是我想避免子查询。有没有办法得到我的结果的总和?

这是第一个查询:

SELECT TeamID, Count(HomeTeamID) AS LASTCOUNT1
FROM Games LEFT JOIN Teams as team1
ON Games.HomeTeamID = team1.TeamID
GROUP BY TeamID;

这是第二个查询:

SELECT TeamID, Count(AwayTeamID) AS LASTCOUNT2
FROM Games LEFT JOIN Teams as team2
ON Games.HomeTeamID = team2.TeamID
GROUP BY TeamID;

结果:

|--TeamID--|--LASTCOUNT1--|
|    1     |       8      |
|    2     |       8      |
|    3     |       8      |
|    4     |       8      |
|    5     |       8      |
|    6     |       8      |
|    7     |       8      |
|    8     |       8      |

|--TeamID--|--LASTCOUNT2--|
|    1     |       8      |
|    2     |       8      |
|    3     |       8      |
|    4     |       8      |
|    5     |       8      |
|    6     |       8      |
|    7     |       8      |
|    8     |       8      |

在没有带有联合的子查询的情况下,如何获得所需的结果?

|--TeamID--|--LASTCOUNT1--|--LASTCOUNT2--|--TOTALCOUNT--|
|    1     |       8      |       8      |      16      |
|    2     |       8      |       8      |      16      |
|    3     |       8      |       8      |      16      |
|    4     |       8      |       8      |      16      |
|    5     |       8      |       8      |      16      |
|    6     |       8      |       8      |      16      |
|    7     |       8      |       8      |      16      |
|    8     |       8      |       8      |      16      |

谢谢!

1 个答案:

答案 0 :(得分:4)

大概,您想计算每个团队的主场和客场比赛的次数。在SQL Server中,您可以取消数据透视和聚合:

SELECT v.TeamID, SUM(ishome) as num_homes, SUM(is_away) as num_aways
FROM Teams t CROSS APPLY
     (VALUES (HomeTeamID, 1, 0), (AwayTeamId, 0, 1)
     ) v(TeamId, ishome, isaway)
GROUP BY v.TeamID;