我在数据库中有一个表,记录着学生的成绩,如下所示:

| id     | criteriaid   |  mark     | studentid     |
| 1      | 5            |  62       | 5             |
| 2      | 6            |  54       | 5             |
| 3      | 7            |  48       | 5             |


然后将其链接到Criteria表,如下所示:

| id     | title        |
| 5      | Presentation |
| 6      | Communication|
| 7      | Research     |


像这样的学生桌:

| id     |firstname     | lastname       |
| 10     |Joe           | Bloggs         |


虽然将表连接在一起没有问题,但看起来可能像这样:

| id | firstname | lastname  |  criteria     | mark     |
| 10 | Joe       | Bloggs    |  Presentation | 62       |
| 10 | Joe       | Bloggs    |  Communication| 54       |
| 10 | Joe       | Bloggs    |  Research     | 48       |


我一直在尝试使用数据透视表教程,但无法获得所需的结果。我认为这是一个动态数据透视表。 (条件必须是动态的)。这就是我要的:

| id | firstname | lastname  |  Presentation | Communication | Research  |
| 10 | Joe       | Bloggs    |       62      |      54       |     48    |


目前,我正在尝试按照此处trouble with mysql pivot table的建议进行硬编码

SELECT s.firstname, s.lastname, m.mark,
  max(case when c.title = 'Attitude' then m.mark end) attitude,
  max(case when c.title = 'Acting' then m.mark end) acting,
  max(case when c.title = 'Presentation' then m.mark end) presentation,
  max(case when c.title = 'Voice' then m.mark end) voice
from marks m
LEFT JOIN criteria c ON m.criteriaid = c.id
LEFT JOIN students s ON s.id = m.studentid


现在,它运行良好,但是我需要一个动态解决方案。我将继续尝试-如果有人可以帮助,我们将不胜感激。

我现在到这里

    SET @sql = NULL;
    SELECT
      GROUP_CONCAT(DISTINCT
        CONCAT(
          'max(case when c.title = ''',
          title,
          ''' then m.mark end) AS ',
          replace(title, ' ', '')
        )
      ) INTO @sql
    from criteria;

    SET @sql = CONCAT('SELECT s.firstname, s.lastname,
    ', @sql,'
    from marks m
    LEFT JOIN criteria c ON m.criteriaid = c.id
    LEFT JOIN students s ON s.id = m.studentid
    group by s.id;');

    PREPARE stmt FROM @sql;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;


这可能可以工作,但是在PHPMyAdmin中不起作用...寻找解决方案!

最佳答案

很难看到如何制作一个可以根据表中的数据而具有不同列的sql表,但是您可以获得所需的一些内容。

您可以使用以下查询:

SELECT studentid,
   MAX(CASE WHEN criteriaid=5 THEN mark END) AS Presentation,
   MAX(CASE WHEN criteriaid=6 THEN mark END) AS Communication,
   MAX(CASE WHEN criteriaid=7 THEN mark END) AS Research
FROM marks
GROUP BY studentid


那没有回答您的问题-而是在SQL中而不是在php中完成了大部分工作。您可能可以根据表中的条件在PHP中构造SQL语句。

关于php - 动态数据透视表MySql,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24704713/

10-08 21:19
查看更多