您可以使用 aCASE
和聚合:
select persid,
max(case when taskid = 1 then status end) as Task1,
max(case when taskid = 2 then status end) as Task2
from course
group by persid
如果您想包含课程信息:
select persid,
course,
max(case when taskid = '1' then status end) as Task1,
max(case when taskid = '2' then status end) as Task2
from course
group by persid, course
order by course, persid
请参阅带有演示的 SQL Fiddle
如果您有未知数量的任务,那么您可以使用准备好的语句来动态生成:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when taskid = ''',
taskid,
''' then status end) AS Task_',
taskid
)
) INTO @sql
FROM course;
SET @sql = CONCAT('SELECT persid, course, ', @sql, '
FROM course
group by persid, course
order by course, persid');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
请参阅带有演示的 SQL Fiddle