简体   繁体   中英

how do I do a nested case in mysql?

observe the following line used in a select statement

(case when p1 = 0 then 1 else (p2-p1)/p1 end) as delta_pct,

this line gives the percentage change between p1 and p2, and if p1 is 0 it returns 1 to avoid the divide by 0 error. but it gives 1 if p2 is also 0 which is incorrect. how do I modify his line to account for that case as well?

something like

case when p1 = 0
    case when p2 = 0
        then 0
    then 1
else (p2-p1)/p1

You could use a CASE expression with more levels to cover all edge cases:

CASE WHEN p1 = 0 AND p2 = 0 THEN 0
     WHEN p1 = 0 THEN 1
     ELSE (p2 - p1) / p1 END AS percentage

normally instead of nested case you can use case expressione with several AND condition for cover your logic but i you really need nested case

but i you really need nested case

case 
when p1 = 0 THEN 
    case when p2 = 0
         then 0
         ELSE 1 
         END 
else (p2-p1)/p1
END delta_pct

as you can cleary see in this case the use of composite and condition is more easy

CASE WHEN p1 = 0 AND p2 = 0 THEN 0
    WHEN p1 = 0 THEN 1
 ELSE (p2 - p1) / p1 END delta_pct 

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