【发布时间】:2013-05-09 15:04:09
【问题描述】:
我知道您可以在带有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
但是,当我执行此操作时出现错误。
我能够实现最终目标的唯一方法是在select 子句中使用case 语句,这并不漂亮。
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
有没有更好的办法?
【问题讨论】:
-
CASE 声明就是你的做法。您不能在 UNPIVOT 函数中使用别名。
-
@bluefeet:该死的太快了。我害怕那个。
-
请注意,Oracle 支持“as”语法,所以这不是一个牵强的需求。
标签: sql-server-2008 tsql unpivot