2015-01-14 105 views
0

我想要做的是通過使用WHERE LienType ='No Private'從case語句中創建的Private Benefits別名來縮小查詢範圍。我會怎麼做?在WHERE子句中使用別名SQL

SELECT DISTINCT ClientId 
,ClientFirstName 
,ClientLastName 
, Case when (select COUNT(*) 
       from FullProductView fpvb 
       where fpvb.clientid=fpva.clientid 
       and fpvb.Lientype ='Private Lien') = 0 then 'No Private' 
     else 'Private Yes' end 'Private Benefits' 
from fullproductview fpva 
WHERE CaseId = 420 
Order By 'Private Benefits' 
+0

我認爲,解決他的問題不重複,但查詢的重組: 選擇 \t客戶端Id, \t ClientFirstName, \t ClientLastName, \t CASE \t \t WHEN SUM(CASE WHEN LienType = '私人連戰' THEN 1 ELSE 0 END)> 0 \t \t THEN '私人是' \t \t ELSE '私人否' \t END PrivateBenefits FROM \t FullProductView FPVA WHERE \t CaseId = 420 GROUP BY \t客戶端Id, \t ClientFirstName, \t ClientLastName ORDER BY \t CASE \t \t WHEN SUM(CASE WHEN LienType = '私人連' THEN 1 ELSE 0 END)> 0 \t \t THEN'Private Yes' \t \t ELSE'Private No' \t END; –

回答

1

你不能直接。在WHERE子句中使用計算字段的唯一兩個選項是使用計算字段或子查詢創建視圖。我認爲創建一個視圖是一個簡單的方法。

編輯

試試這個:

CREATE VIEW vw_MyView AS 
SELECT DISTINCT ClientId 
,ClientFirstName 
,ClientLastName 
, Case when (select COUNT(*) 
       from FullProductView fpvb 
       where fpvb.clientid=fpva.clientid 
       and fpvb.Lientype ='Private Lien') = 0 then 'No Private' 
     else 'Private Yes' end 'Private Benefits' 
from fullproductview fpva 
WHERE CaseId = 420 

然後,你可以這樣做:

SELECT * from vw_MyView WHERE LienType = 'No Private' Order By 'Private Benefits' 

而且是不使用的字段名稱空間是一個好主意。你需要檢查這是否適用於你的數據庫引擎(至於你沒有提到)。

+0

你如何構建視圖? – EAJ5