首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用pivot将行转换为列

使用pivot将行转换为列
EN

Stack Overflow用户
提问于 2014-05-13 11:41:38
回答 1查看 122关注 0票数 0

这张桌子现在是我的了。

代码语言:javascript
复制
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

我想转换为:

代码语言:javascript
复制
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。我怎么才能转换。

EN

回答 1

Stack Overflow用户

发布于 2014-05-13 11:47:09

您可以使用alternate来使用select查询进行透视,如下所示。

代码语言:javascript
复制
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,最后的查询将是:

代码语言:javascript
复制
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; 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23622419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档