Há 3 coisas para pensar 1) Como gerar dinamicamente um monte de max(case when 2) atribuindo algo para agrupar o case when's by - neste caso eu gero um número de linha usando uma variável 3) alguns de seus cargos contêm espaço em branco que removo para a geração de cabeçalhos de coluna
set @sql =
(select concat('select ', gc, ' from
(select name,job_title,
if (job_title <> @p, @rn:=1 ,@rn:[email protected]+1) rn,
@p:=job_title p
from t
cross join (select @rn:=0,@p:=null) r
order by job_title
) s group by rn;') from
(select
group_concat('max(case when job_title = ', char(39),job_title ,char(39),' then name else char(32) end ) as ',replace(job_title,char(32),'')) gc
from
(
select distinct job_title from t
) s
) t
)
;
Gera este código sql
select max(case when job_title = 'Fireman' then name else char(32) end ) as Fireman,
max(case when job_title = 'Driver' then name else char(32) end ) as Driver,
max(case when job_title = 'Analyst' then name else char(32) end ) as Analyst,
max(case when job_title = 'Postman' then name else char(32) end ) as Postman,
max(case when job_title = 'Research Manager' then name else char(32) end ) as ResearchManager
from
(select name,job_title,
if (job_title <> @p, @rn:=1 ,@rn:[email protected]+1) rn,
@p:=job_title p
from t
cross join (select @rn:=0,@p:=null) r
order by job_title
) s group by rn;
Que pode ser submetido ao sql dinâmico
prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;
resultado
+---------+--------+---------+---------+-----------------+
| Fireman | Driver | Analyst | Postman | ResearchManager |
+---------+--------+---------+---------+-----------------+
| Sam | Tomas | Lisa | Marcus | Mary |
| Peter | Chen | Stephan | | |
| | | Albert | | |
+---------+--------+---------+---------+-----------------+
3 rows in set (0.00 sec)