Sum columns with null values in oracle

后端 未结 9 1748
抹茶落季
抹茶落季 2020-12-09 15:27

I want to add two numbers together but when one of those numbers is null then the result is null. Is there a way around this. I could simply do it in the code but I would

相关标签:
9条回答
  • 2020-12-09 16:07

    In some cases, nvl(sum(column_name),0) is also required. You may want to consider your scenarios.

    For example, I am trying to fetch the sum of a particular column, from a particular table based on certain conditions. Based on the conditions,

    1. one or more rows exist in the table. In this case I want the sum.
    2. rows do not exist. In this case I want 0.

    If you use sum(nvl(column_name,0)) here, it would give you null. What you might want is nvl(sum(column_name),0).

    This may be required especially when you are passing this result to, say, java, have the datatype as number there because then this will not require special null handling.

    0 讨论(0)
  • 2020-12-09 16:07
    select type, craft, sum(NVL(regular, 0) + NVL(overtime, 0)) as total_hours
    from hours_t
    group by type, craft
    order by type, craft
    
    0 讨论(0)
  • 2020-12-09 16:10

    The other answers regarding the use of nvl() are correct however none seem to address a more salient point:

    Should you even have NULLs in this column?

    Do they have a meaning other than 0?

    This seems like a case where you should have a NOT NULL DEFAULT 0 on th ecolumn

    0 讨论(0)
提交回复
热议问题