2017-02-24 66 views
0

我已經在MY SQL服務器中創建視圖,其中我需要使用CASE條件來滿足需求。如何在SQL視圖中創建新列時使用條件

select 
    cast([SIR Per Occ] as float) * 1000000 as [SIR Per Occ], 
    cast([SIR Agg] as float) * 1000000 as [SIR Agg], 
    cast([Per Occ Limit Between] as float) * 1000000 as [Per Occ Limit Between], 
    cast((cast([SIR Per Occ] as float)) + (cast([Per Occ Limit Between] as float)) as float) * 1000000 as [Policy Occ Attachment], 
    cast((cast([SIR Agg] as float)) + (cast([Per Occ Limit Between] as float)) as float) * 1000000 as [Policy Agg Attachment] 
from IT.dbo.Policy_find 

但在我的任務,如果[Per Occ Limit Between]NULL值,那麼我就需要假設它是零和上面的代碼應該是工作爲以下邏輯:

Policy Occ Attachment = [SIR Per Occ] 
Policy Agg Attachment = [SIR Agg] 

我將如何實現這種情況在select子句中沒有使用where的條件?

回答

2

只需在列定義中使用CASE而不是列名(CASE MSDN here)。

EDIT(對於SQL Server):如果你想刪除NULL值,你可以使用ISNULL(YOUR_EXPRESSION, '')

+0

情況下,當[每測站極限的]爲null,則0,否則,投([每測站極限的作爲浮動)* 1000000年底爲[每測站極限的] ..這個工作在某種程度上,但它仍然認爲0作爲字符串,並不加起來 – Mike

+0

你仍然可以使用CAST在你的情況? 'CAST(如果exp THEN 0 ELSE 1 END,float)'這有點矯枉過正,但應該可以正常工作 – Lostblue

0

我不能決定,如果這是我的 「SQL服務器」 或 「MY SQL」 服務器。

但是,實際上,對於這個特定的查詢並不重要。

使用COALESCE

select 
    cast([SIR Per Occ] as float) * 1000000 as [SIR Per Occ], 
    cast([SIR Agg] as float) * 1000000 as [SIR Agg], 
    cast([Per Occ Limit Between] as float) * 1000000 as [Per Occ Limit Between], 
    cast((cast([SIR Per Occ] as float)) + (cast(COALESCE([Per Occ Limit Between],0) as float)) as float) * 1000000 as [Policy Occ Attachment], 
    cast((cast([SIR Agg] as float)) + (cast([Per Occ Limit Between] as float)) as float) * 1000000 as [Policy Agg Attachment] 
from IT.dbo.Policy_find 
相關問題