给出以下查询,该查询会生成学生及其分配到的群组的列表:
SELECT mdl_user.lastname, mdl_user.firstname, mdl_cohort.name
FROM mdl_cohort
INNER JOIN mdl_cohort_members ON mdl_cohort_members.cohortid = mdl_cohort.id
INNER JOIN mdl_user ON mdl_cohort_members.userid = mdl_user.id
ORDER BY mdl_user.lastname, mdl_cohort.name
是否可以生成一个结果,将每个队列名称显示一次,最好作为列名称,并将每个学生分配到下面列出的该队列?像这样的事情:
Engineering Cohort Administrative Cohort IT Cohort
------------------ --------------------- ---------
John Doe Jane Smith Jane Doe
Jane Smith John Smith John Doe
Dan Jones Dana Jones Dana Jones
最佳答案
这可以编写脚本......纯粹基于 SQL 的方法非常丑陋。以下方法将结果加载到表中(每个结果的计数器从 1 递增),然后连接在一起。最后的联合模拟完整的外部连接,以确保没有任何队列被遗漏。
set @admin:=0;
set @eng:=0;
set @it:=0;
drop table if exists administrative;
create table administrative as
select (@admin := @admin + 1) as counter
, cohort
from ( select concat(mdl_user.firstname, ' ', mdl_user.lastname) as cohort
from mdl_cohort
inner join mdl_cohort_members on (mdl_cohort_members.cohortid = mdl_cohort.id)
inner join mdl_user on (mdl_cohort_members.userid = mdl_user.id)
where mdl_cohort.name='Administrative Cohort'
order by mdl_user.lastname, mdl_user.firstname) as admin;
drop table if exists engineering;
create table engineering as
select (@eng := @eng + 1) as counter
, cohort
from ( select concat(mdl_user.firstname, ' ', mdl_user.lastname) as cohort
from mdl_cohort
inner join mdl_cohort_members on (mdl_cohort_members.cohortid = mdl_cohort.id)
inner join mdl_user on (mdl_cohort_members.userid = mdl_user.id)
where mdl_cohort.name='Engineering Cohort'
order by mdl_user.lastname, mdl_user.firstname) as eng;
drop table if exists it;
create table it as
select (@it := @it + 1) as counter
, cohort
from ( select concat(mdl_user.firstname, ' ', mdl_user.lastname) as cohort
from mdl_cohort
inner join mdl_cohort_members on (mdl_cohort_members.cohortid = mdl_cohort.id)
inner join mdl_user on (mdl_cohort_members.userid = mdl_user.id)
where mdl_cohort.name='IT Cohort'
order by mdl_user.lastname, mdl_user.firstname) as it;
select admin.cohort as `Administrative Cohorts`,
eng.cohort as `Engineering Cohorts`,
it.cohort as `IT Cohorts`
from administrative admin
left join engineering eng on(eng.counter=admin.counter)
left join it on (it.counter=admin.counter)
union
select '' as `Administrative Cohorts`,
eng.cohort as `Engineering Cohorts`,
it.cohort as `IT Cohorts`
from engineering eng
left join it on (it.counter=eng.counter)
where not exists (select 1
from administrative
where counter=eng.counter)
union
select '' as `Administrative Cohorts`,
'' as `Engineering Cohorts`,
it.cohort as `IT Cohorts`
from it
where not exists (select 1
from administrative
where counter=it.counter)
and not exists (select 1
from engineering
where counter=it.counter);
关于MySQL:类似数据透视的查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42703109/