SET @EE='';SELECT @EE:=GROUP_CONCAT(@EE,'sum(if(val=\'',val,'\'',',id,0)) as ','''',val,'''') from (select DISTINCT val from hl_test)a;SET @str=CONCAT('select ',@EE,' from hl_test group by id');PREPARE stmt from @str;EXECUTE stmt;