检查是否为空

时间:2017-10-14 16:54:25

标签: sql oracle

我有一个任务来检查字段是否包含null,如果是,我必须将其更改为0然后求和。

这就是表格的外观

Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EMPNO                                     NOT NULL NUMBER(4)
 ENAME                                              VARCHAR2(10)
 JOB                                                VARCHAR2(9)
 MGR                                                NUMBER(4)
 HIREDATE                                           DATE
 SAL                                                NUMBER(7,2)
 COMM                                               NUMBER(7,2)
 DEPTNO                                             NUMBER(2)

我必须将字段SAL和COMM

相加

所以我创建了这个SQL代码。

select ename, NVL(sal,0)+NVL(comm,0) money from emp;

它输出的一切正确

ENAME           MONEY
---------- ----------
SMITH             800
ALLEN            1900
WARD             1750
JONES            2975
MARTIN           2650
BLAKE            2850
CLARK            2450
SCOTT            3000
KING             5000
TURNER           1500
ADAMS            1100

ENAME           MONEY
---------- ----------
JAMES             950
FORD             3000
MILLER           1300

但是现在我必须使用 CASE 语句来做同样的事情。 但我似乎失败了我尝试的一切,也许是因为我还没有理解SQL中的案例如何运作良好。

我尝试的代码

select ename, 
case 
when comm is null then sal+0
when sal is null then comm+0
end nauda
from emp;

并输出了

ENAME           MONEY
---------- ----------
SMITH             800
ALLEN
WARD
JONES            2975
MARTIN
BLAKE            2850
CLARK            2450
SCOTT            3000
KING             5000
TURNER
ADAMS            1100

ENAME           MONEY
---------- ----------
JAMES             950
FORD             3000
MILLER           1300

2 个答案:

答案 0 :(得分:2)

我更喜欢coalesce()nvl()因为它是ANSI标准:

select ename, coalesce(sal, 0) + coalesce(comm, 0) as money
from emp;

这是解决问题的正确方法。但是,如果你想使用case,这是一种方式:

select ename,
       (case when sal is not null and comm is not null then sal + comm
             when sal is not null then sal
             when comm is not null then comm
             else 0
        end) as money
from emp;

答案 1 :(得分:0)

您还可以使用子查询,这样您就可以通过各种方式操作数据。也可以帮助在较小的数据集上做事。

select
  ename,
  comm,
  sal
from
 (select 
    ename, 
    nvl(com, 0) as comm,
    nvl(sal, 0) as sal
  from 
    emp)
相关问题