2014-12-08 4 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 ... Выбрать в зависимости от значения столбца feature_value, но can not, похоже, построить правильный запрос для этого. Все идеи?

ответ

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' 
Смежные вопросы