这张桌子现在是我的了。
Name PhoneType Number
a Cellular 303-333-3333
a WorkPHone 444-444-4444
b Workphone 222-222-2222
c Cellular 111-111-1111
c WorkPHone 333-333-3333
c HomePhone 888-888-8888
d Cellular 999-999-9999
d WorkPHone 777-777-7777
d HomePhone 111-222-3333我想转换为:
Name Cellular Workphone Homephone
a 303-333-3333 444-444-4444 222-222-2222
b 222-222-2222
c 111-111-1111 333-333-3333 888-888-8888
d 999-999-9999 777-777-7777 111-222-3333我试过Pivot,但做不到,因为我不能对电话号码使用聚合函数,因为它是nvarchar。我怎么才能转换。
发布于 2014-05-13 11:47:09
您可以使用alternate来使用select查询进行透视,如下所示。
with xx as(
select 'a' namee,'cellular' typee,'303-333-3333' numberr from dual union all
select 'a' namee,'WorkPHone' typee,'444-444-4444' numberr from dual union all
select 'b' namee,'WorkPHone' typee,'222-222-2222' numberr from dual union all
select 'c' namee,'cellular' typee,'111-111-1111' numberr from dual union all
select 'c' namee,'WorkPHone' typee,'333-333-3333' numberr from dual union all
select 'c' namee,'HomePhone' typee,'888-888-8888' numberr from dual
)
select
x.namee,
max(case when x.typee='cellular' then x.numberr else '' end) as CELLULAR,
max(case when x.typee='WorkPHone' then x.numberr else '' end) as WORKPHONE,
max(case when x.typee='HomePhone' then x.numberr else '' end) as HOMEPHONE
from xx x
group by x.namee
order by x.namee;编辑:
xx表应替换为您的表名。假设您的表名为my_table,最后的查询将是:
select x.Name ,
max(case when x.PhoneType='cellular' then x.Number else '' end) as CELLULAR,
max(case when x.PhoneType='WorkPHone' then x.Number else '' end) as WORKPHONE,
max(case when x.PhoneType='HomePhone' then x.Number else '' end) as HOMEPHONE
from
my_table x
group by x.Name
order by x.Name; https://stackoverflow.com/questions/23622419
复制相似问题