2013-03-09 63 views
0

我有一個表名用戶,在這個表中用戶有他們的名字和類別(例如:student,employee)。Mysql查詢顯示同一列相對於類別兩次

現在我想顯示其他表格中的用戶,如同所有學生將在學生列中顯示的用戶一樣,並且所有員工用戶都將顯示在Employee列中。

實施例:

用戶表:

Name  Category 
John  Student 
Jack  Student 
Fred  Employee 

輸出表:

ID Student Employee 
1  John  
2  Jack 
3     Fred 

會有什麼顯示該表中的查詢。

+1

什麼你試過嗎? &顯示一些代碼請不清楚 – Sedz 2013-03-09 11:59:49

+0

請查看[格式幫助](http://stackoverflow.com/editing-help)並格式化您的問題以使其可讀。 – 2013-03-09 12:00:05

+0

http://stackoverflow.com/questions/7932548/how-to-get-the-category-wise-values-related-to-user – 2013-03-09 12:02:11

回答

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  ║ 
╚════╩═════════╩══════════╝ 

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; 
+0

謝謝,它的作品:) – 2013-03-09 12:12:13

+0

不客氣':D' – 2013-03-09 12:13:50