如何将行更改为列?

时间:2013-08-29 16:25:12

标签: sql oracle oracle11g pivot

我有一张如下表:

Name        Org
aaaa        bbb 
aaaa        bbbb 
aaaa        bbbbb
bbbb        cccc

如何将oracle sql更改为以下格式

Name   Org1       Org2       Org3
aaaa   bbb        bbbb       bbbbb
bbbb   cccc

2 个答案:

答案 0 :(得分: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) |

答案 1 :(得分:0)

您可以使用PIVOT来实现此目标。

this这样的东西: -

select *
from
  (select fk_department
   from employee)
   pivot
    (count(fk_department)
      for fk_department in ('INT', 'WEL', 'CEN', 'POL'));