我有一个表格,其格式为:
EmpNumber,PreferredPhoneType,MobilePhone,WorkPhone,HomePhone
10041,Work Phone,,342423,
我正在尝试使用:
select empnumber,
DECODE(PreferredPhoneType,'Work Phone', 'W',
'Mobile', 'M',
'Home','H') result,
MobilePhone,WorkPhone,HomePhone from xx_phone;
但这是检索所有值而不管列类型。我希望结果是这样的,如果手机类型是' W'第三栏应该是工作电话号码。
类似的东西:
EmpNumber,PhoneType,Number
1000 M 336363
2828 W 88373
3838 H 837373
是否有这样做的功能?
答案 0 :(得分:2)
这是CASE表达式的典型应用。
我创建了一些输入数据,显示了不同的可能情况。我还创建了一个小表,显示每个描述使用哪个单字母代码。如果您已经拥有这些表格,则不需要" WITH子句"在顶部,从select id.empnumber....
with input_data (empnumber, preferredphonetype, mobilephone, workphone, homephone) as (
select 10041, 'Work Phone' , null , '342423' , null from dual union all
select 10043, 'Mobile Phone' , '332211' , '443341' , '288300' from dual union all
select 10034, null , '330403' , '588923' , '455433' from dual union all
select 10046, 'Home Phone' , '433223' , '048423' , null from dual
),
phone_types (phonetype, description) as (
select 'M', 'Mobile Phone' from dual union all
select 'W', 'Work Phone' from dual union all
select 'H', 'Home Phone' from dual
)
select id.empnumber, pt.phonetype,
case id.preferredphonetype
when 'Mobile Phone' then mobilephone
when 'Work Phone' then workphone
when 'Home Phone' then homephone
end as phonenumber
from input_data id left outer join phone_types pt
on id.preferredphonetype = pt.description;
EMPNUMBER PHONETYPE PHONENUMBER
---------- --------- -----------
10043 M 332211
10041 W 342423
10046 H
10034
注意10046如何拥有"家庭电话"显示为首选,但她在表中没有家庭电话号码;并且10034具有所有三个电话号码,但没有首选电话类型,因此该员工的两个值都为空(空)。