在同一个选择中使用别名

时间:2013-05-17 14:47:24

标签: sql-server-2008 select alias columnname

我设置了一个像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]

甚至可能吗?

1 个答案:

答案 0 :(得分:5)

,您无法在同一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