SELECT ID,
MAX(CASE WHEN Category = 'Student' THEN Name ELSE NULL END) Student,
MAX(CASE WHEN Category = 'Employee' THEN Name ELSE NULL END) Employee
FROM User
GROUP BY ID
结果
╔════╦═════════╦══════════╗
║ ID ║ STUDENT ║ EMPLOYEE ║
╠════╬═════════╬══════════╣
║ 1 ║ John ║ (null) ║
║ 2 ║ Jack ║ (null) ║
║ 3 ║ (null) ║ Fred ║
╚════╩═════════╩══════════╝
更新 1
如果您有其他类别,则首选动态 sql ,
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(case when Category = ''',
Category,
''' then Name end) AS ',
Category
)
) INTO @sql
FROM User;
SET @sql = CONCAT('SELECT ID, ', @sql, '
FROM User
GROUP BY ID');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;