3

I know that you can use an alias on a column with pivot, but I'd like to use an alias with unpivot as well.

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

However I get an error when I do this.

The only way I've been able to accomplish my end goal is to use a case statement in the select clause, which isn't pretty.

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

Is there a better way?

4

3 回答 3

3

另一种方法是在 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
于 2016-05-29T23:11:43.867 回答
1

您不能在 UNPIVOT 函数内分配别名,因此您必须使用该CASE表达式。

另一种方法是使用 aUNION ALL并立即放置新值:

select userid, 3000 as ContactMethod, homePhone as ContactMethodValue
from users 
union all
select userid, 3001 as ContactMethod, OfficePhone as ContactMethodValue
from users 
union all
select userid, 3002 as ContactMethod, CellPhone as ContactMethodValue
from users 
union all
select userid, 3003 as ContactMethod, Website as ContactMethodValue
from users 
union all
select userid, 3005 as ContactMethod, homePhone as ContactMethodValue
from users 
于 2013-05-09T15:14:54.113 回答
0

您可以将别名包装在另一个 select 语句中,以便识别别名,然后从那里取消透视:

select * from
        (select UserId,
            HomePhone      as [3000]
            OfficePhone    as [3001]
            CellPhone      as [3002]
            Fax            as [3003]
            Website        as [3005]
        from aliasedUsers) P
        unpivot (ContactMethodValue for ContactMethod in ([3000],[3001],[3002],[3003],[3005])) as unpvt
于 2021-06-18T22:18:22.497 回答