感谢您在Advance中的所有帮助。
我在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查询或Pivot / php数组输出到表中,以便为HTML表输出做好准备;
Date | Tom | Terry | Lucas
Mon Yes No Yes
Tue No No Yes
Wed Yes Yes No
答案 0 :(得分: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;