简体   繁体   English

SQL 合并两行ID相同但列值不同的行

[英]SQL Merge two rows with same ID but different column values

I am trying to merge different rows into one when they have the same id but different column values.当它们具有相同的 id 但不同的列值时,我试图将它们合并为一个。

    (table1)

    id       colour

    1        red
    1        blue
    2        green
    2        red

I would like this to be combine so that the result is:我希望将其结合起来,以便结果是:

    id     colour1    colour2

    1      red        blue
    2      green      red

There is no limit for number of colors. colors的数量没有限制。 It can range depending on the id.它的范围取决于 id。

Any help would be appreciated.任何帮助,将不胜感激。 Thanks in advance.提前致谢。

This would work for your specific example这适用于您的具体示例

select left(colours,locate(',',colours)-1) as colour1, right(colours, length(colours)- locate(',',colours)) as colour2 from (select id, group_concat(colour) as colours from table1 group by id) concatenation

not very general or robust.不是很一般或健壮。

If the set of values (colours) were fixed, I'd prefer to pivot it like this:如果一组值(颜色)是固定的,我更喜欢 pivot 像这样:

select id, sum(RED) as RED, sum(GREEN) as GREEN, sum(BLUE) as BLUE from (select id, colour='red' as RED, colour='green' as GREEN, colour='blue' as BLUE from table1) coded group by id;

but that wasn't the output format you requested.但这不是您要求的 output 格式。

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

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