简体   繁体   中英

How to use condition while creating new column in SQL view

I have create a view in MY SQL server, where I need to use CASE condition in order to satisfy a requirement.

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

But in my task, if the [Per Occ Limit Between] is NULL values, then I need to assume it be as zero and the above code should be working as following logic :

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

How would I implement such scenario in the select clause without using where condition?

Just use CASE with your column definition instead of the column name ( CASE MSDN here ).

EDIT (For SQL Server) : If you want to remove NULL values, you can use ISNULL(YOUR_EXPRESSION, '')

I couldn't decide if it's MY "SQL server" or "MY SQL" server.

But, actually, for this specific query it doesn't matter.

use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM