0

感谢您提前提供的所有帮助。

我在 MySQL PHPmyAdmin 中有一个名为“数据”的表,如下所示;

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
4

1 回答 1

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;
于 2013-02-22T15:59:21.923 回答