繁体   English   中英

插入..选择,同一列不同的值

[英]Insert..Select, same column different values

我有这张桌子,上面有:

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

您要将列转换为行,可以为此使用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

一种方法是使用条件聚合:

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;

使用此选择

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' 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM