Reputation: 17840
I have the following table
ID1 ID2 Type
1 x A
1 y A
1 z B
.
.
.
I want it transformed like this
ID1 A B
1 x,y z
Any idea how to go about it
The best I have been able to get is 2 rows, one with A values and 1 with B values using group_concat(id2) and group by ID1,Type
Upvotes: 0
Views: 540
Reputation: 9974
I can get it down to one row, but with extra commas :-(
select ID1,
group_concat( if( `Type` = 'A', ID2, '') ) A,
group_concat( if( `Type` = 'B', ID2, '') ) B
from tab
group by ID1
Gives:
+------+------+------+
| ID1 | A | B |
+------+------+------+
| 1 | x,y, | ,,z |
+------+------+------+
Supplying NULL instead of '' fixes this:
select ID1,
group_concat( if( `Type`='A', ID2, NULL)) A,
group_concat( if(`Type`='B', ID2, NULL)) B
from tab
group by ID1;
Gives:
+------+------+------+
| ID1 | A | B |
+------+------+------+
| 1 | x,y | z |
+------+------+------+
Upvotes: 2