Sql Server:如何使用别名进行逆透视?

Mas*_*ity 4 t-sql unpivot sql-server-2008

我知道您可以在列上使用别名 with ,但我也pivot想使用别名 with 。unpivot

select UserId
,      ContactMethod
,      ContactMethodValue
from Users
unpivot (
    ContactMethodValue for ContactMethod in
    (   HomePhone      as [3000]
    ,   OfficePhone    as [3001]
    ,   CellPhone      as [3002]
    ,   Fax            as [3003]
    ,   Website        as [3005]
    )
 ) as unpvt
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做时,我收到错误。

我能够实现最终目标的唯一方法是caseselect子句中使用语句,这并不漂亮。

select UserId
,      ( case ContactMethod
         when 'HomePhone'    then 3000
         when 'OfficePhone'  then 3001
         when 'CellPhone'    then 3002
         when 'Fax'          then 3003
         when 'Website'      then 3005
         end ) as ContactMethod
,      ContactMethodValue
from Users
unpivot (
    ContactMethodValue for ContactMethod in
    (   HomePhone
    ,   OfficePhone
    ,   CellPhone
    ,   Fax
    ,   Website
    )
 ) as unpvt
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

Jef*_*eff 5

另一种方法是在unpivot之前使用别名,如下所示:

;with aliasedUsers as (
    select
        UserId,
        HomePhone      as [3000]
        OfficePhone    as [3001]
        CellPhone      as [3002]
        Fax            as [3003]
        Website        as [3005]
)
select UserId
,      ContactMethod
,      ContactMethodValue
from aliasedUsers
unpivot (
    ContactMethodValue for ContactMethod in
    (   [3000]
    ,   [3001]
    ,   [3002]
    ,   [3003]
    ,   [3005]
    )
) as unpvt
Run Code Online (Sandbox Code Playgroud)