Oracle-如果一列不为空,则将另一列留空

6ovsh4lw  于 2022-10-04  发布在  Oracle
关注(0)|答案(2)|浏览(169)

我有一张简单的table

create table employees (empno int primary key, empname varchar(30), 
emailaddress varchar(30), phonenumber varchar(10))

EMPNO   EMPNAME EMAILADDRESS    PHONENUMBER
1         Emma  emma@gmail.com  82354566
2          Tom  tom@gmail.com   984537665
3          Bob  Bob@gmail.com

我想显示结果,例如,如果特定客户的电话号码不为空,则将其电子邮件地址设置为空白,否则将按原样显示电子邮件地址。

我想要的结果应该是

EMPNO   EMPNAME EMAILADDRESS    PHONENUMBER
1         Emma                  82354566
2         Tom                   984537665
3         Bob   Bob@gmail.com

它应该显示为空白,并且不应该显示not null

我尝试了以下几种方法

select *
case 
when phonenumber is not null 
then '' as emailaddress
end
from employees

但上面写着ORA-00923: FROM keyword not found where expected

这是我的演示-DB Fiddle

mzmfm0qo

mzmfm0qo1#

更改为:

select empno, empname, phonenumber,
case 
when phonenumber is not null 
then '' 
else emailaddress
end as emailaddress
from employees

DBFIDDLE

juud5qan

juud5qan2#

正如xQbert所说,您的Case构造是错误的,但是在*和Case表达式之间也缺少逗号,如果您将*与其他任何东西组合在一起,那么它必须以表名或别名为前缀。

因此,您可以这样做:

select e.*,
  case when phonenumber is not null then null else emailaddress end as etc
from employees e

或略短(依赖于丢失的else计算结果为空):

select e.*,
  case when phonenumber is null then emailaddress end as etc
from employees e

或者,如果有电话号码,则根本不显示电子邮件地址:

select
  empno,
  empname,
  case when phonenumber is null then emailaddress end as emailaddress,
  phonenumber
from employees

EMPNO|EMPNAME|EailAddress|PHONENUMBER
-|-|
1|Emma|NULL|82354566
2|汤姆||984537665
3|Bob|Bob@gmail.com|

或者,如果您只想将其中之一显示为单列:

select
  empno,
  empname,
  case when phonenumber is null then emailaddress else phonenumber end as etc
from employees

或者使用coalesce而不是case

select
  empno,
  empname,
  coalesce(phonenumber, emailaddress) as etc
from employees

EMPNO|EMPNAME|ETC
-|-|
1|艾玛|82354566
2|汤姆|984537665
3|Bob|Bob@gmail.com

db<>fiddle

相关问题