我有一个表像下面:如何将行更改为列?
Name Org
aaaa bbb
aaaa bbbb
aaaa bbbbb
bbbb cccc
如何使用的Oracle SQL改变成下面的格式
Name Org1 Org2 Org3
aaaa bbb bbbb bbbbb
bbbb cccc
我有一个表像下面:如何将行更改为列?
Name Org
aaaa bbb
aaaa bbbb
aaaa bbbbb
bbbb cccc
如何使用的Oracle SQL改变成下面的格式
Name Org1 Org2 Org3
aaaa bbb bbbb bbbbb
bbbb cccc
有,你可以得到结果的几种方法。我显示的两个版本都使用row_number()
来帮助将行转换为列。
可以使用聚合函数CASE表达式:
select
name,
max(case when seq = 1 then org end) org1,
max(case when seq = 2 then org end) org2,
max(case when seq = 3 then org end) org3,
max(case when seq = 4 then org end) org4,
max(case when seq = 5 then org end) org5
from
(
select name, org,
row_number() over(partition by name
order by org) seq
from yourtable
) d
group by name;
见SQL Fiddle with Demo。或者,因为你使用的是Oracle 11g中,你可以使用旋转功能对行转换为列:
select name,
Org1,
Org2,
Org3,
Org4,
Org5
from
(
select name, org,
row_number() over(partition by name
order by org) seq
from yourtable
) d
pivot
(
max(org)
for seq in ('1' as Org1, '2' as Org2,
'3' as Org3, '4' as Org4,
'5' as Org5)
) piv
见SQL Fiddle with Demo。两者都给出结果:
| NAME | ORG1 | ORG2 | ORG3 | ORG4 | ORG5 |
| aaaa | bbb | bbbb | bbbbb | (null) | (null) |
| bbbb | cccc | (null) | (null) | (null) | (null) |
非常感谢 – haoyun
您使用的是哪个版本的Oracle?你打算每个名字都有一定数量的组织吗? – Taryn
Oracle 11是的。我认为5是每个名称可以有的最多组织数 – haoyun