2013-02-22 69 views
0

感謝您在Advance中提供的所有幫助。SQL查詢:行列數據透視到PHP陣列/ HTML輸出

我在MySQL PHPmyAdmin中有一個名爲'data'的表,像這樣;

Primary | Date| User | Response 
    1  Mon Tom  Yes 
    2  Mon Terry No 
    3  Mon Lucas Yes 
    4  Tue Tom  No 
    5  Tue Terry No 
    6  Tue Lucas Yes 
    7  Wed Tom  Yes 
    8  Wed Terry Yes 
    9  Wed Lucas No 

我怎麼輸出到一個表,通過最有可能的SQL查詢或數據透視/ PHP數組,這個準備HTML表格輸出;

Date | Tom | Terry | Lucas 
Mon Yes No  Yes 
Tue No No  Yes 
Wed Yes Yes  No 

回答

1
SELECT Date, 
     MAX(CASE WHEN user = 'Tom' THEN Response ELSE NULL END) Tom, 
     MAX(CASE WHEN user = 'Terry' THEN Response ELSE NULL END) Terry , 
     MAX(CASE WHEN user = 'Lucas' THEN Response ELSE NULL END) Lucas 
FROM tableName 
GROUP BY Date 

,如果你有數目不詳的days,動態SQL是更優選,

SET @sql = NULL; 
SELECT 
    GROUP_CONCAT(DISTINCT 
    CONCAT(
     'MAX(case when user = ''', 
     user, 
     ''' then Response end) AS ', 
     user 
    ) 
) INTO @sql 
FROM tableName; 

SET @sql = CONCAT('SELECT Date, ', @sql, ' 
        FROM tableName 
        GROUP BY Date'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 
+0

+1其仍然奇怪的查詢:) – Azad 2013-02-22 16:02:18