【问题标题】:Reuse subquery results for other computations with SQL Server使用 SQL Server 将子查询结果重用于其他计算
【发布时间】:2013-07-15 18:30:49
【问题描述】:

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

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

【问题讨论】:

    标签: sql ms-access subquery


    【解决方案1】:

    在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 2014-07-04
      • 2021-05-06
      • 2019-06-28
      • 1970-01-01
      相关资源
      最近更新 更多