3

で列にエイリアスを使用できることは知っていますが、でもエイリアスpivotを使用したいと思い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

ただし、これを行うとエラーが発生します。

私が最終目標を達成することができた唯一の方法は、節でcaseステートメントを使用することですが、これはきれいではありません。select

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

より良い方法はありますか?

4

3 に答える 3

3

もう 1 つの方法は、次のように、アンピボットの前にエイリアスを設定することです

;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式を使用する必要があります。

別の方法は、 a を使用しUNION 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 に答える