-1

I am trying to merge different rows into one when they have the same id but different column values.

    (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. It can range depending on the id.

Any help would be appreciated! Thanks in advance.

t.niese
  • 39,256
  • 9
  • 74
  • 101
John Doe
  • 89
  • 1
  • 2
  • 7

1 Answers1

0

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:

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.

sonam_zangmo
  • 106
  • 6