0

我有表:

date name hours
--------------
11    peter   12:00
11    peter   11:00
11    john    10:00
12    peter   9:00
12    john   13:00
13    peter   10:00
13    john    16:00

etc...

我只需要制作 MySQL 查询和 PHP 交叉表(不确定这是不是正确的术语),所以它看起来像这样:

        11   |  12   | 13 
-----------------------------------------
john  | 10:00 | 13:00 | 16:00
-----------------------------------------
peter | 12:00 | 9:00  | 10:00
        11:00 | 

到目前为止,我到了:

SELECT date, GROUP_CONCAT(CONCAT_WS('|', name, hours) ORDER BY name) schedule 
FROM days
GROUP BY date

但我觉得我在填充和制作上面的表格时遇到了困难。

4

2 回答 2

1

试试这个查询:

SELECT Name
   ,GROUP_CONCAT(CASE WHEN Date = 11 THEN hours ELSE NULL END) AS `11`
   ,GROUP_CONCAT(CASE WHEN Date = 12 THEN hours ELSE NULL END) AS `12`
   ,GROUP_CONCAT(CASE WHEN Date = 13 THEN hours ELSE NULL END) AS `13`
  FROM days
 GROUP BY Name

您也可以使用此动态查询:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'GROUP_CONCAT(CASE WHEN `Date` = ''',
      `Date`,
      ''' THEN hours ELSE NULL END) AS `',
      `Date`, '`'
    )
  ) INTO @sql
FROM Days;

SET @sql = CONCAT('SELECT Name, ', @sql,'
                     FROM Days
                    GROUP BY Name
                  ');

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

输出:

|  NAME |          11 |    12 |    13 |
---------------------------------------
|  john |       10:00 | 13:00 | 16:00 |
| peter | 12:00,11:00 |  9:00 | 10:00 |

看到这个 SQLFiddle

于 2013-07-25T10:54:16.217 回答
0

如果您执行以下操作:

 SELECT date, name, hours FROM days ORDER BY date

然后要显示它们,您只需要比较日期值,如果它与之前的不同,请创建一个新列。

于 2013-07-25T10:57:38.867 回答