在oracle中使用null值汇总列

Ber*_*yan 28 sql oracle

我想将两个数字加在一起,但当其中一个数字为null时,结果为null.有没有解决的办法.我可以简单地在代码中执行它,但我宁愿在查询中完成它.这是一个oracle数据库.

表结构

hours_t
type     craft    regular       overtime
 A         1        5              0
 A         1        3              1
 B         2        9            <null>
 B         1        4              4
Run Code Online (Sandbox Code Playgroud)

查询

select type, craft, sum(regular + overtime) as total_hours
from hours_t
group by type, craft
order by type, craft
Run Code Online (Sandbox Code Playgroud)

不想要的结果

type   craft   total_hours
  A      1          9
  B      1          8
  B      2        <null>
Run Code Online (Sandbox Code Playgroud)

想要的结果

type    craft   total_hours
  A       1          9
  B       1          8
  B       2          9
Run Code Online (Sandbox Code Playgroud)

zen*_*dar 51

NVL(值,默认值)是您要查找的功能.

select type, craft, sum(NVL(regular, 0) + NVL(overtime, 0) ) as total_hours
from hours_t
group by type, craft
order by type, craft
Run Code Online (Sandbox Code Playgroud)

Oracle有5个与NULL相关的函数:

  1. NVL
  2. NVL2
  3. 合并
  4. NULLIF
  5. LNNVL

NVL:

NVL(expr1, expr2)
Run Code Online (Sandbox Code Playgroud)

NVL允许您使用查询结果中的字符串替换null(作为空白返回).如果expr1为null,则NVL返回expr2.如果expr1不为null,则NVL返回expr1.

NVL2:

NVL2(expr1, expr2, expr3)
Run Code Online (Sandbox Code Playgroud)

NVL2允许您根据指定的表达式是null还是非null来确定查询返回的值.如果expr1不为null,则NVL2返回expr2.如果expr1为null,则NVL2返回expr3.

合并

COALESCE(expr1, expr2, ...)
Run Code Online (Sandbox Code Playgroud)

COALESCE返回表达式列表中的第一个非空expr.至少有一个expr不能是文字NULL.如果所有出现的expr都计算为null,则该函数返回null.

NULLIF

NULLIF(expr1, expr2)
Run Code Online (Sandbox Code Playgroud)

NULLIF比较expr1和expr2.如果它们相等,则该函数返回null.如果它们不相等,则函数返回expr1.您不能为expr1指定文字NULL.

LNNVL

LNNVL(condition)
Run Code Online (Sandbox Code Playgroud)

LNNVL提供了一种简洁的方法来评估条件的一个或两个操作数可能为空时的条件.

有关Oracle SQL函数的更多信息


Ton*_*ews 47

select type, craft, sum(nvl(regular,0) + nvl(overtime,0)) as total_hours
from hours_t
group by type, craft
order by type, craft
Run Code Online (Sandbox Code Playgroud)


cle*_*tus 9

关于使用nvl()的其他答案是正确的,但似乎没有一个解决更突出的问题:

你应该在这个专栏中有NULL吗?

他们有0以外的意思吗?

这似乎是一个你应该在列上有一个NOT NULL DEFAULT 0的情况

  • @Mark Brady,我真的不同意.这并不是"我们有多聪明",而是提出了解决问题的替代方法.OP可能有也可能没有能力更改列,但是注释很有用(如果不是他那么可能对其他读这个帖子的人来说). (2认同)
  • @cletus,我认为这更适合作为对问题的评论,而不是单独的答案. (2认同)

Jos*_*ons 5

NVL评分最高的答案是完全有效的。如果您有兴趣提高SQL代码的可移植性,则可能需要使用CASE,在Oracle和SQL Server中都支持相同的语法:

select 
  type,craft,
  SUM(
    case when regular is null
         then 0
         else regular
    end
    +
    case when overtime is null
         then 0
         else overtime
    end
  ) as total_hours
from 
  hours_t
group by
  type
 ,craft
order by
  type
 ,craft
Run Code Online (Sandbox Code Playgroud)