2013-05-17 81 views
0

一旦我設置了一個像這樣的列名稱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

沒有,你不能在同一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 
+1

嗚哇我喜歡它!當你看到它完成時,這是非常明顯的...謝謝 – phadaphunk

+0

@PhaDaPhunk - 隨時歡迎您:) –