2014-12-08 3 views
0

나는 함께이 테이블을 가지고 다음Insert..Select, 같은 열에 다른 값

part_id | feature_name | feature_value | feature_unit | 
_____________________________________________________________ 
    1  |  Weight  |  2   |  kg  | 
    1  |  Color  |  Blue  |    | 
    1  | Description |description here|    | 

내가 다른 (신규) 테이블

part_id | description | color | weight | 
_______________________________________________ 
    1  |description here| Blue | 2kg | 

에 있었다 이러한 장소를하고 싶었다 무엇 필자는 feature_value 컬럼의 값에 따라 Insert..Select를 사용하는 것을 생각했지만 이럴 경우 올바른 쿼리를 작성할 수없는 것 같습니다. 어떤 아이디어입니까?

답변

1

열을 행으로 변환하는 경우 case based aggregation을 사용할 수 있습니다. 이 작업을 수행하는

INSERT into newTable(part_id, description, color, weight) 
SELECT part_id 
     max(case when feature_name ='Description' 
       then feature_value end) as description, 
     max(case when feature_name ='Color' 
       then feature_value end) as Color, 
     max(case when feature_name ='weight' 
       then concat(feature_value,feature_unit) end) as weight 
FROM my_table 
GROUP BY part_id 
+0

와우, 생각하지 않았을. – sumpreto

0

한 가지 방법은 조건부 집계 함께 :

select part_id, 
     max(case when feature_name = 'description' then feature_value end) as description, 
     max(case when feature_name = 'color' then feature_value end) as color, 
     max(case when feature_name = 'weight' then concat(feature_value, feature_unit) end) as weight 
from thistable 
group by part_id; 
0

사용이 선택

select t1.part_id, t1.feature_value, t2.feature_value, t3.feature_value from table t1 inner join table t2 on t1.part_id = t2.part_id and t2.feature_name = 'Color' inner join table t3 on t1.part_id =t3.part_id and t3.feature_name='Weight' where t1.feature_name = 'Description'