2015-09-25 93 views
2

如果這是可能高級MySQL查詢,組1列

我有在鹼這樣的:

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

+1

使用[GROUP_CONCAT](http://www.w3resource.com/mysql/aggregate-functions-and -grouping/aggregate-functions-and-grouping-group_concat.php) – amdixon

+0

使用group_concat(column2,',')和按列1組 –

回答

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

SQL Fiddle

如果你想與空間()而不是逗號(,)分離,
ŧ母雞在group_concat中指定separator ' '

然後查詢將會像下面:

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

SQL Fiddle

+0

tnx。好。 但如果可能的話:不在一列... –

+0

然後,每個值在不同的列? – Wanderer