开发者

Transform Data in MySQL

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,Typ开发者_JS百科e


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    |
+------+------+------+
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜