考えるべき3つのことがあります1)最大の束を動的に生成する方法(2の場合はケースをグループ化するために何かを割り当てる-この場合は変数を使用して行番号を生成します3)いくつかの役職には次のものが含まれます列ヘッダーの生成のために削除した空白
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
)
;
この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;
動的SQLに送信できるもの
prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;
結果
+---------+--------+---------+---------+-----------------+
| Fireman | Driver | Analyst | Postman | ResearchManager |
+---------+--------+---------+---------+-----------------+
| Sam | Tomas | Lisa | Marcus | Mary |
| Peter | Chen | Stephan | | |
| | | Albert | | |
+---------+--------+---------+---------+-----------------+
3 rows in set (0.00 sec)