If inside if MySQL

1

I'm doing a query on mysql and so far I have this

SUM(IF(val1 IS NULL, val2, val1 )) AS total

But is it possible to do something like that?

SUM(IF(val1 IS NULL, if(val2 is null, 0, val2) val1 )) AS total

Where I say that if val1 is null put val2 but before putting val2 ask again if this null to put 0

    
asked by Santiago Muñoz 04.10.2016 в 18:56
source

1 answer

1

I suggest you change to COALESCE

The idea is to return the first value not null

Staying

SUM(COALESCE(val1,val2,0)) AS total

For this case val1 = null, val2 = 5 , it will return 5 because it is the first one that is not null from left to right

For the case val1 = null, val2 = null will return 0 because 0 is the first non-zero value

For the case val1 = 10, val2 = 5 will return 10 because 10 is the first non-zero value

Based on the comment

We can add a case

SUM(COALESCE(case when val1 = 0 then null else val1 end,val2,0)) AS total
    
answered by 04.10.2016 / 19:01
source