使用列名作为 Phone 数字的值

Use column names as values for Phone Number

我有一个 table,其中 phone 个数字分成单独的列单元格 phone、家庭phone、工作phone 和其他phone。我想进行某种转换,将所有 phone 拉入一列,但在下一列中显示 phone 关系,因此目前我的数据如下所示:

CellPhone  HomePhone  workPhone   OtherPhone
8756785468 8756944858 8756944903  8937944858

我想看的:

TelephoneNumber  TelephoneRelationship
8756785468       Cell
8756944858       Home
8756944903       Work
8937944858       Other

我的创建语句很简单:

Create Table ods.Telephone(
    CellPhoneNumber varchar(10) null,
    HomePhoneNumber varchar(10) null,
    WorkPhoneNumber varchar(10) null,
    OtherPhoneNumber Varchar(10) null
);

我建议使用 union all 取消透视。

这是一个标准的跨 RDBMS 解决方案,在我看来,它的语法更容易理解和记忆,而且通常性能与供应商特定的解决方案一样好,甚至更好:

select id, CellPhoneNumber TelephoneNumber, 'Cell' TelephoneRelationship from Telephone
union all select id, HomePhoneNumber,  'Home'  from Telephone
union all select id, WorkPhoneNumber,  'Work'  from Telephone
union all select id, OtherPhoneNumber, 'Other' from Telephone

Demo on DB Fiddle

示例数据:

ID | CellPhoneNumber | HomePhoneNumber | WorkPhoneNumber | OtherPhoneNumber
-: | :-------------- | :-------------- | :-------------- | :---------------
 1 | 8756785468      | 8756944858      | 8756944903      | 8937944858      

结果:

id | TelephoneNumber | TelephoneRelationship
-: | :-------------- | :--------------------
 1 | 8756785468      | Cell                 
 1 | 8756944858      | Home                 
 1 | 8756944903      | Work                 
 1 | 8937944858      | Other                

通过CROSS APPLY

还有一个选择
Select A.ID
      ,B.*
 From  Telephone A
 Cross Apply ( values (CellPhoneNumber,'Cell')
                     ,(HomePhoneNumber,'Home')
                     ,(WorkPhoneNumber,'Work')
                     ,(OtherPhoneNumber,'Other')
             ) B(TelephoneNumber,TelephoneRelationship)

Returns

ID  TelephoneNumber TelephoneRelationship
1   8756785468      Cell
1   8756944858      Home
1   8756944903      Work
1   8937944858      Other