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 ║
╚════╩═════════╩══════════╝
UPDATE 1
如果有其他類別,則動態SQL爲p簡稱,
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;
什麼你試過嗎? &顯示一些代碼請不清楚 – Sedz 2013-03-09 11:59:49
請查看[格式幫助](http://stackoverflow.com/editing-help)並格式化您的問題以使其可讀。 – 2013-03-09 12:00:05
http://stackoverflow.com/questions/7932548/how-to-get-the-category-wise-values-related-to-user – 2013-03-09 12:02:11