如果可能的话
我有这样的基础:
AAA 1
AAA 2
BBB 1
BBB 2
BBB 3
,结果必须像这样
AAA 1 2
BBB 1 2 3
或
AAA 1,2
BBB 1,2,3
TNX
答案 0 :(得分:4)
使用GROUP_CONCAT
。
<强>查询强>
select column1,
group_concat(column2 separator ',') as column2
from tableName
group by column1;
<强>结果强>
+---------+---------+
| column1 | column2 |
+---------|---------+
| AAA | 1,2 |
| BBB | 1,2,3 |
+---------+---------+
如果您想要用空格( )
而不是逗号(,)
分隔,
然后在separator ' '
中指定group_concat
。
然后查询将如下所示:
select column1,
group_concat(column2 separator ' ') as column2
from tableName
group by column1;
<强>结果强>
+---------+---------+
| column1 | column2 |
+---------|---------+
| AAA | 1 2 |
| BBB | 1 2 3 |
+---------+---------+
Read more about group_concat
here
UPDATE
如果您需要单独列中的每个column2
值,
那么您可能需要执行动态SQL查询。
<强>查询强>
set @query = null;
select
group_concat(distinct
concat(
'max(case when column2 = ''',
column2, ''' then column2 end) as Value_',column2
)
) into @query
from tableName ;
set @query = concat('select column1, ', @query, ' from tableName
group by column1
');
prepare stmt from @query;
execute stmt;
deallocate prepare stmt;
<强>结果强>
+---------+---------+---------+---------+
| column1 | Value_1 | Value_2 | Value_3 |
+---------+---------+---------+---------+
| AAA | 1 | 2 | (null) |
| BBB | 1 | 2 | 3 |
+---------+---------+---------+---------+