1

我读过一些问题,但对我来说不清楚,我不能使用枢轴

我有下一张桌子:

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 表达式并正确转置我的表格?有更好的解决方案吗?

提前致谢

4

2 回答 2

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
于 2012-08-09T17:45:49.520 回答
1

当您执行 aGROUP 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;
于 2012-08-09T17:40:58.527 回答