2013-07-15 29 views
1

我有一组这样的查询在Access中运行良好,但是当我尝试使它们成为MS SQL中的视图或存储过程时,它告诉我子查询别名不是在查询中稍后用于在其上运行计算的有效列。重复使用SQL Server的其他计算的子查询结果

下面是我在访问:

SELECT T.DistrictNum, 

(select count(winner) from TournyGames2013 where type='Pool 1' and winner=T.DistrictNum) AS TeamWins, 
(select count(loser) from TournyGames2013 where type='Pool 1' and loser=T.DistrictNum) AS TeamLoses, 
([TeamWins]+[TeamLoses]) AS GameTotal 
FROM TournyTeams2013 AS T 
WHERE T.Pool=1 

世界如何让我从这个一个可行的视图或存储过程?
谢谢,温柔,我的第一篇文章在这里。

回答

3

在SQL Server中(与遵守ANSI标准的其他数据库一样),您不能在定义它的相同级别select处引用别名。

您可以轻松地解决这个问题使用子查询:

select t.*, ([TeamWins]+[TeamLoses]) AS GameTotal 
from (SELECT T.DistrictNum, 
      (select count(winner) from TournyGames2013 where type='Pool 1' and winner=T.DistrictNum) AS TeamWins, 
      (select count(loser) from TournyGames2013 where type='Pool 1' and loser=T.DistrictNum) AS TeamLoses 
     FROM TournyTeams2013 AS T 
     WHERE T.Pool=1 
    ) t 
+0

这个伟大工程,谢谢! –