Search code examples
sqlstored-procedurespostgresql-9.3

How to use coalesce to take sum


Can I use sum() in coalesce()?

I want to use it in a stored function in Postgres.

For example

case (COALESCE(t3.Count3,0)+ COALESCE(t2.Count2,0) >= t4.Count4::float) 
then ( select (t4.Count4::float/((t3.Count3::float)+(t2.Count2::float))) * 100 as Count5 ) 
else ''0'' 
end as Count5

Solution

  • It's hard to tell what you're trying to do here because there are multiple issues in the code. Also though your title mentions SUM your code doesn't include it (though you do have + but that's not the same).

    If this is part of a SELECT statement, then I'm guessing what you want is:

    SELECT
    CASE
        WHEN COALESCE(t3.Count3,0)+ COALESCE(t2.Count2,0) >= t4.Count4::float
        THEN 100 * t4.Count4::float/(COALESCE(t3.Count3::float,0)+COALESCE(t2.Count2::float,0))
        ELSE 0
    END as Count5
    FROM MyTable