我有一个表名用户,在此表中,用户有他们的名字和类别(例如:学生,员工)。
现在我想在其他表格中显示用户按类型分隔的用户,就像学生将在学生列中显示的所有用户一样,所有员工用户都将显示在员工列中。
示例:
用户表:
Name Category
John Student
Jack Student
Fred Employee
输出表:
ID Student Employee
1 John
2 Jack
3 Fred
显示该表的查询是什么。
答案 0 :(得分:2)
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
RESULT
╔════╦═════════╦══════════╗
║ 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;