转置表Oracle 10

时间:2012-08-09 17:36:24

标签: sql oracle10g

我已经阅读了一些问题,但对我来说并不清楚,我不能使用支点

我有下一张桌子:

ID AREA CAR
1   A1   A
1   A2   B
1   A3   C
2   A1   D
2   A2   E
3   A2   F
3   A3   G

我想要一些像

ID  AREA1  CAR1  AREA2  CAR2  AREA3  CAR3
1     A1     A    A2     B      A3    C         
2     A1     D    A2     D     null  null                   
3    null   null  A2     F      A3    G                    

区域数量是固定的,只有A1,A2,A3。

我试过

SELECT     id, area1,car1,area2,car2
FROM       (  SELECT        id,
                        case when AREA='A1' then AREA else NULL end area1,
                        case when AREA='A1' then CAR else NULL end car1,   
                        case when AREA='A2' then AREA else NULL end area2,
                        case when AREA='A2' then CAR else NULL end car2,
                        case when AREA='A3' then AREA else NULL end area3,
                        case when AREA='A3' then CAR else NULL end car3
          FROM        TABLA
          GROUP BY    id );

但我明白了:

"not a GROUP BY expression"

如果有正确的GROUP BY表达式并正确转置我的表,我该怎么办? 有没有更好的解决方案呢?

提前致谢

2 个答案:

答案 0 :(得分:2)

不幸的是,Oracle 10上没有PIVOT函数。您的查询已关闭,但不需要将其包含在另一个查询中:

select id,
  min(case when area = 'A1' then area end) area1,
  min(case when area = 'A1' then car end) car1,
  min(case when area = 'A2' then area end) area2,
  min(case when area = 'A2' then car end) car2,
  min(case when area = 'A3' then area end) area3,
  min(case when area = 'A3' then car end) car3
from yourTable
group by id

答案 1 :(得分:1)

当您执行GROUP BY时,您需要聚合您未分组的任何列。你可能想要像

这样的东西
SELECT     id, area1,car1,area2,car2
FROM       (  SELECT        id,
                        max( case when AREA='A1' then AREA else NULL end) area1,
                        max( case when AREA='A1' then CAR else NULL end) car1,   
                        max( case when AREA='A2' then AREA else NULL end) area2,
                        max( case when AREA='A2' then CAR else NULL end) car2,
                        max( case when AREA='A3' then AREA else NULL end) area3,
                        max( case when AREA='A3' then CAR else NULL end) car3
          FROM        TABLA
          GROUP BY    id );

您还可以将聚合和GROUP BY移动到外部查询

SELECT     id, max(area1),max(car1),max(area2),max(car2)
FROM       (  SELECT        id,
                        case when AREA='A1' then AREA else NULL end area1,
                        case when AREA='A1' then CAR else NULL end car1,   
                        case when AREA='A2' then AREA else NULL end area2,
                        case when AREA='A2' then CAR else NULL end car2,
                        case when AREA='A3' then AREA else NULL end area3,
                        case when AREA='A3' then CAR else NULL end car3
          FROM        TABLA)
GROUP BY    id;