Insert..Select,同一列不同的值

时间:2014-12-08 02:06:37

标签: mysql sql

我的表格中包含以下内容:

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列的值,但似乎无法为此构建正确的查询。任何想法?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

答案 2 :(得分: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'