2014-12-08 31 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 | 

我想使用Insert..Select取決於feature_value列的值,但似乎無法爲此構建正確的查詢。任何想法?

回答

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 2014-12-08 02:22:24

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'