2012-08-09 42 views
1

我读过一些问题,但目前尚不清楚对我来说,我不能用枢轴移调一个表甲骨文10

我有下表:

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表达和正常转我的表? 有没有更好的解决方案呢?

在此先感谢

+0

我读过 http://stackoverflow.com/questions/1788011/transpose-select-results-with-oracle 但我不明白:( – OscarSan 2012-08-09 17:37:58

回答

2

遗憾的是,在Oracle 10没有旋转功能您所查询的是接近,但有不需要包装其他查询里面:

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 
+0

谢谢,我觉得自己像一个傻瓜xD ..这很容易 – OscarSan 2012-08-09 17:51:12

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; 
+0

谢谢贾斯汀,我现在明白了! – OscarSan 2012-08-09 17:50:51