1

我在 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

我到底如何从中创建一个有效的视图或存储过程?
谢谢,温柔点,我在这里的第一篇文章。

4

1 回答 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
于 2013-07-15T18:36:06.947 回答