2012-05-17 65 views
0

我正嘗試使用我在查詢中創建的列別名,在同一個查詢中的公式中爲不同的列創建。我在這裏做錯了什麼,我該如何解決它?這裏的代碼,以便更好地解釋一下:嘗試在查詢中使用列別名時出現「無效列」

SELECT TestTabI.Month, TestTabI.Year, AccessEntityList.Region, 
AccessEntityList.[Audit Tier], AccessEntityList.[Parent Group], 
case 
when AccessEntityList.[Jurisdiction]='U.S.' 
then [NF PTI] 
else 0 
end AS [US Pretax Income], 

case 
when AccessEntityList.[Jurisdiction]='Non-U.S.' 
then [NF PTI] 
else 0 
end AS [FN Pretax Income], 

[US Pretax Income]+[FN Pretax Income] AS [Total Pretax Income] FROM AccessEntityList 
INNER JOIN TestTabI ON AccessEntityList.[Entity Number] = 
TestTabI.[Entity Number] WHERE (((TestTabI.Month)=12) AND ((TestTabI.Year)=2010) 

「[美國稅前收入] + AS [FN稅前收入] [總稅前收入]」 給我的錯誤:

Msg 207, Level 16, State 1, Line 7 
Invalid column name 'US Pretax Income'. 
Msg 207, Level 16, State 1, Line 7 
Invalid column name 'FN Pretax Income'. 
+0

這是一個UGLY查詢,格式和名稱不會變得更糟!僅供參考,所有這些工作:'選擇1作爲一個;選擇1作爲「one!」;選擇1作爲[one!];選擇1作爲'one!';'我會檢查你的列名拼寫,並且他們在你認爲他們的表格中。 –

回答

0

我通常使用無我的列名中有空格,所以我不熟悉這個括號語法。你確定它適用於別名聲明嗎?

爲了您的別名試圖用反引號替換所以括號:

end AS `US Pretax Income`, 
+1

在SQL Server中(標記了什麼問題),您將得到** Msg 102,Level 15,State 1,Line 1如果您嘗試按照您的建議使用back-tick,則會在'''附近使用錯誤的語法。 –

1

如果你把你的case語句在cross apply可以使用別名。

select TestTabI.Month, 
     TestTabI.Year, 
     AccessEntityList.Region, 
     AccessEntityList.[Audit Tier], 
     AccessEntityList.[Parent Group], 
     C.[US Pretax Income], 
     C.[FN Pretax Income], 
     C.[US Pretax Income]+C.[FN Pretax Income] AS [Total Pretax Income] 
from AccessEntityList 
    inner join TestTabI 
    on AccessEntityList.[Entity Number] = TestTabI.[Entity Number] 
    cross apply 
    (
    select case 
       when AccessEntityList.[Jurisdiction]='U.S.' 
       then [NF PTI] 
       else 0 
      end as [US Pretax Income], 
      case 
       when AccessEntityList.[Jurisdiction]='Non-U.S.' 
       then [NF PTI] 
       else 0 
      end as [FN Pretax Income] 
    ) as C 
where TestTabI.Month=12 and TestTabI.Year=2010 
2

你不能使用你只是在SELECT定義對同一SELECT的別名。無論是使用CTE或派生表爲此:

SELECT A.*, [US Pretax Income]+[FN Pretax Income] AS [Total Pretax Income] 
FROM (
SELECT TestTabI.Month, TestTabI.Year, AccessEntityList.Region, 
     AccessEntityList.[Audit Tier], AccessEntityList.[Parent Group], 
     case when AccessEntityList.[Jurisdiction]='U.S.' then [NF PTI] 
     else 0 end AS [US Pretax Income], 
     case when AccessEntityList.[Jurisdiction]='Non-U.S.' 
     then [NF PTI] else 0 end AS [FN Pretax Income] 
FROM AccessEntityList 
INNER JOIN TestTabI 
ON AccessEntityList.[Entity Number] = TestTabI.[Entity Number] 
WHERE (((TestTabI.Month)=12) AND ((TestTabI.Year)=2010)) A 
+0

或者如果你想這樣做的方式錯綜複雜,你可以將你的兩個case語句複製到別名中:) - 但我會用Lamak說的方法 – Charleh

相關問題