0

我正在做以下查询

    SELECT 
        p.id
        ,q.name
        ,pa.result
    FROM
        postulant_answers as pa
    LEFT OUTER JOIN postulants as p ON (p.id = pa.postulant_id)
    LEFT OUTER JOIN questions as q ON (q.id = pa.question_id);

这向我展示了以下结果:

    +------+--------------+--------+
    | id   | name         | result |
    +------+--------------+--------+
    |    9 | Question 1   |     15 |
    |    9 | Question 2   |     70 |
    |    9 | Question 3   |     75 |
    |  591 | Question 1   |     15 |
    |  591 | Question 2   |     70 |
    |  591 | Question 3   |     75 |

但我需要更多类似的东西:

    +------+------------+------------+------------+
    | id   | Question 1 | Question 2 | Question 3 |
    +------+------------+------------+------------+
    |    9 |         15 |         70 |         75 |
    |  591 |         15 |         70 |         75 |

我可以在一个查询中做到这一点吗?
任何帮助,将不胜感激

4

1 回答 1

2

这被称为枢轴,但 MySQL 没有枢轴函数,因此您可以使用聚合函数和 a 来实现它CASE

SELECT p.id,
  max(case when q.name = 'Question 1' then pa.result end) Question1,
  max(case when q.name = 'Question 2' then pa.result end) Question2,
  max(case when q.name = 'Question 3' then pa.result end) Question3
FROM postulant_answers as pa
LEFT OUTER JOIN postulants as p 
  ON (p.id = pa.postulant_id)
LEFT OUTER JOIN questions as q 
  ON (q.id = pa.question_id)
group by p.id

请参阅带有演示的 SQL Fiddle

结果:

|  ID | QUESTION1 | QUESTION2 | QUESTION3 |
-------------------------------------------
|   9 |        15 |        70 |        75 |
| 591 |        15 |        70 |        75 |

如果您有已知数量的问题,上述方法非常有用,但如果问题数量未知,那么您可以使用准备好的语句,类似于以下内容:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when q.name = ''',
      q.name,
      ''' then pa.result end) AS ',
      replace(name, ' ', '')
    )
  ) INTO @sql
FROM questions;

SET @sql = CONCAT('SELECT p.id, ', @sql, ' 
                  FROM postulant_answers as pa
                  LEFT OUTER JOIN postulants as p 
                    ON (p.id = pa.postulant_id)
                  LEFT OUTER JOIN questions as q 
                    ON (q.id = pa.question_id)
                  group by p.id');

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

请参阅带有演示的 SQL Fiddle

于 2012-12-05T18:17:00.960 回答