使用SQL Server重新使用子查询结果进行其他计算

时间:2013-07-15 18:30:50

标签: sql ms-access subquery

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

以下是我在Access中的内容:

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

我在世界上如何制作一个有效的视图或存储过程?
谢谢,温柔,我的第一篇文章。

1 个答案:

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