5

一旦我设置了这样的列名 SUM(someColumn) AS [ColumnName],之后我该如何使用它?

假设我构建了一个这样的查询:

SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
       SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
       -- I need [TotalFooBar]

在同一个选择中,我想要 和 的[TotalFoo]总数[TotalBar]。是否可以参考这些专栏?我可以做到这一点:

SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
       SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
       SUM((foo.A + foo.B + foo.C + foo.D + foo.E) +
           (bar.A + bar.B + bar.C + bar.D + bar.E)) AS [TotalFooBar]

在这个例子中没关系,但我有更多的专栏,很难理解。然后如果我必须使用这个列([TotalFooBar])怎么办?我每次都必须重写整个 SUM 吗?
我正在寻找的是这样的:

SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
       SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
       SUM([TotalFoo] + [TotalBar]) AS [TotalFooBar]

甚至可能吗?

4

1 回答 1

10

,您不能在同一SELECT语句中执行此操作,但您可以使用子查询:

SELECT 
  TotalFoo,
  TotalBar,
  TotalFoo + TotalBar AS TotalFooBar
FROM
(
    SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
           SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
           ...
    FROM ...
) AS sub
...

或 CTE:

WITH CTE
AS
(
   SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
          SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
          ...
   FROM ...
)
SELECT 
  TotalFoo,
  TotalBar,
  TotalFoo + TotalBar AS TotalFooBar
FROM CTE
于 2013-05-17T14:49:40.977 回答