简体   繁体   中英

Select NULL if a calculated column value is negative in SQL

I have the following piece of sql below. The second line (commented out) contains my addition of a check to see if the calculation returns a negative value in which case it should select NULL . This case is within a block of multiple other case statements. Since my approach means running the same calculation twice is there a better alternative or more efficient method to selecting NULL if the value of this calculated column is negative, rather than doing two similar calculations?

Thanks

CASE 
            WHEN M.ALPHA = 'B' OR T.CT IN (0.001, 0.002) THEN NULL
        --  WHEN ((M.VAL / NULLIF (M.VAL2, 0)) / (NULLIF (T.VAL, 0) / T.VAL2)) < 0 THEN NULL
            ELSE (M.VAL / NULLIF (M.VAL2, 0)) / (NULLIF (T.VAL, 0) / T.VAL2) 
         END As WORLD

You could move the calculation to a subquery. For example:

select  case
        when CalculatedColumn > 42 then 'Hot'
        when CalculatedColumn < 42 then 'Cold'
        else 'Answer'
        end as Description
from    (
        select  2 * col1 + 3 as CalculatedColumn
        from    YourTable
        ) SubQuery

Sometimes it's clearer to define the subquery in a with clause:

; with  SubQuery as
        (
        select  2 * col1 + 3 as CalculatedColumn
        from    YourTable
        ) SubQuery
select  case
        when CalculatedColumn > 42 then 'Hot'
        when CalculatedColumn < 42 then 'Cold'
        else 'Answer'
        end as Description
from    SubQuery

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