-1

我有一个如下表:

Name        Org
aaaa        bbb 
aaaa        bbbb 
aaaa        bbbbb
bbbb        cccc

如何使用 oracle sql 更改为以下格式

Name   Org1       Org2       Org3
aaaa   bbb        bbbb       bbbbb
bbbb   cccc
4

2 回答 2

1

有几种方法可以获得结果。我展示的两个版本都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,您可以使用 PIVOT 函数将行转换为列:

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) |
于 2013-08-29T17:11:44.887 回答
0

您可以使用PIVOT来实现这一点。

这样的东西:-

select *
from
  (select fk_department
   from employee)
   pivot
    (count(fk_department)
      for fk_department in ('INT', 'WEL', 'CEN', 'POL'));
于 2013-08-29T16:27:11.053 回答