Er zijn 3 dingen om over na te denken 1) Hoe dynamisch een aantal max te genereren (case wanneer 2) iets toewijzen om de case te groeperen wanneer is door - in dit geval genereer ik een rijnummer met behulp van een variabele 3) sommige van uw functietitels bevatten witruimte die ik verwijder voor het genereren van kolomkoppen
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
)
;
Genereert deze sql-code
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;
Die kan worden ingediend bij dynamische sql
prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;
resultaat
+---------+--------+---------+---------+-----------------+
| Fireman | Driver | Analyst | Postman | ResearchManager |
+---------+--------+---------+---------+-----------------+
| Sam | Tomas | Lisa | Marcus | Mary |
| Peter | Chen | Stephan | | |
| | | Albert | | |
+---------+--------+---------+---------+-----------------+
3 rows in set (0.00 sec)