數據如下:
ID SEG MMM NNN
123 1 A AA
123 2 B BB
123 3 C CC
我想轉換成下面的格式:
ID MMM_1 NNN_1 MMM_2 NNN_2 MMM_3 NNN_3
123 A AA B BB C CC
MMM_1,NNN_1就是SEG=1時的MMM,NNN,2和3類似。
請問怎麼通過sql語句實現?
/*
create temporary table Tmp(ID int,SEG int, MMM varchar(10), NNN varchar(10));
insert into Tmp value
(123, 1, 'A', 'AA'),
(123, 2, 'B', 'BB'),
(123, 3, 'C', 'CC');
*/
set @sql='';
select group_concat('max(case when SEG=',SEG,' then MMM else '''' end) as ', 'MMM_',SEG,'
,max(case when SEG=',SEG,' then NNN else '''' end) as NNN_',SEG,'
' ) into @sql from Tmp;
set @sql=concat('SELECT ID,',@sql,' from Tmp group by ID');
prepare stmt from @sql;
execute stmt ;
DEALLOCATE PREPARE stmt;
/*
'123', 'A', 'AA', 'B', 'BB', 'C', 'CC'
*/