Oracle 中带条件的列到行

Columns to Rows with a condition in Oracle

我有一个 table,列的格式为 :

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;

但这是在检索所有值,而不考虑列类型。我希望结果是这样的,如果 phone 类型是 'W',则第三列的结果应该是工作 phone 编号。

类似于:

 EmpNumber,PhoneType,Number
    1000       M         336363
    2828       W          88373
    3838       H         837373

是否有这样做的功能?

这是CASE表达式的典型应用。

我创建了一些输入数据,显示了不同的可能情况。我还创建了一个小的 table 来显示每个描述使用了哪个单字母代码。如果你已经有这些tables,你不需要顶部的"WITH clause",从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 如何将 "Home Phone" 显示为首选,但她在 table 中没有住宅 phone 号码;和 10034 具有所有三个 phone 号码,但没有首选 phone 类型,因此该员工的两个值都留空(空)。