2017-03-03 98 views
1

我使用Microsoft SQL Server。必要性,這種情況

我經常遇到這樣的代碼:

select (a*5 + a*4 + a*3) as a1 --some complicated and very long manipulation of column 'a' 
into #Temp1 
from Table1 

select a1, case when a1 > 5 then 1 else 0 end as myResult 
from #Temp1 

我曾嘗試使用:

select (a*5 + a*4 + a*3) as a1, case when a1 > 5 then 1 else 0 end as myResult 
from Table1 

,並提示錯誤爲 'A1' 無效的列名。我明白這一點,但對於像我這樣的情況是有辦法避免創建#TEMP1一步?

編輯: 我知道這樣的編碼結構爲:

select (a*5 + a*4 + a*3) as a1, case when (a*5 + a*4 + a*3) > 5 then 1 else 0 end as myResult 
from Table1 

有關列一個非常令人費解的操作「A」的代碼變得不可讀。

+0

a1是一個alisas,只要sql server知道沒有a1,alisase的行爲更像是標籤而不是實際的列 – Phil3992

回答

4
您在同一SELECT語句中提出,但你可以例如像這樣做

您不能引用列:

select a1, case when a1 > 5 then 1 else 0 end as myResult 
from (
    select (a*5 + a*4 + a*3) as a1 --some complicated and very long manipulation 
    from Table1 
) X 

你也可以做熱膨脹係數,或使用外類似的事情適用於使用select創建新列。

0

你可以輕易地計算在你選擇的兩倍,但我重讀你的問題,並意識到你說的是計算更先進一點,這個,所以我會與詹姆斯個Z答案去。

select (a*5 + a*4 + a*3) as a1, case when (a*5 + a*4 + a*3) > 5 then 1 else 0 end as myResult 
from Table1 
+1

請花時間解釋您的解決方案,以便其他人可以瞭解並從中學習! :-) – Shawn

相關問題