oracle 如果不为空,请选择三列之一

rmbxnbpk  于 2023-03-07  发布在  Oracle
关注(0)|答案(3)|浏览(181)
NAME | TELEPHONE_1 | TELEPHONE_2 | TELEPHONE_3
Max  | 00491633888 | NULL        | NULL
Soph | NULL        | NULL        | NULL
Pes  | NULL        | 0049163232  | 0049111111

对于Max,输出应为00491633888对于Soph,输出应为NULL对于Pes,输出应为找到的第一个条目。因此电话2 -〉0049163232

SELECT
    CASE WHEN TELEPHONE_1  IS NOT NULL THEN TELEPHONE_1 
    ELSE WHEN TELEPHONE_2 IS NOT NULL THEN TELEPHONE_2  
    ELSE WHEN TELEPHONE_3 IS NOT NULL THEN TELEPHONE_3 
    ELSE NULL END AS TELEPHONE
FROM test

我试过了,但没用。

bxpogfeg

bxpogfeg1#

使用coalesce;它将返回第一个非空值:

select name,
  COALESCE(telephone_1, telephone_2, telephone_3) as telephone
from test

演示:

SQL> with test (name, telephone_1, telephone_2, telephone_3) as
  2    (select 'Max' , '00491633888', null        , null         from dual union all
  3     select 'Soph', null         , null        , null         from dual union all
  4     select 'Pes' , null         , '0049163232', '0049111111' from dual
  5    )
  6  select name,
  7    COALESCE(telephone_1, telephone_2, telephone_3) as telephone
  8  from test;

NAME TELEPHONE
---- -----------
Max  00491633888
Soph
Pes  0049163232

SQL>
mf98qq94

mf98qq942#

(my原文):“NVL()函数接受表达式列表并返回第一个非空值”
我错了,NVL()只带2个参数,COALESCE()更标准,更灵活。

vhipe2zx

vhipe2zx3#

您不希望在WHEN之前使用ELSE关键字(删除这些关键字后,代码才能正常工作):

SELECT name,
       CASE
       WHEN TELEPHONE_1 IS NOT NULL THEN TELEPHONE_1 
       WHEN TELEPHONE_2 IS NOT NULL THEN TELEPHONE_2  
       WHEN TELEPHONE_3 IS NOT NULL THEN TELEPHONE_3 
       ELSE NULL
       END AS TELEPHONE
FROM   test

输出:
| 姓名|电话|
| - ------|- ------|
| 马克斯|00491633888|
| 索菲|* 无效 *|
| 佩斯|0049163232|
也可以使用COALESCE(ANSI标准的一部分):

SELECT name,
       COALESCE(TELEPHONE_1, TELEPHONE_2, TELEPHONE_3) AS TELEPHONE
FROM   test

NVL(这是一个Oracle函数,只接受2个参数):

SELECT name,
       NVL(TELEPHONE_1, NVL(TELEPHONE_2, TELEPHONE_3)) AS TELEPHONE
FROM   test

fiddle

相关问题