2

可能重复:
mysql 数据透视表/交叉表查询

我正在使用 MySQL 和 PHP,我从 JOIN 查询中获得了这个表......

╔═══════╦════════════════╦═══════════════╦════════╗
║ name  ║    last_name   ║ course_name   ║ tries  ║
╠═══════╬════════════════╬═══════════════╬════════╣
║ coco  ║ valencia       ║ Course Num. 1 ║     11 ║
║ coco  ║ valencia       ║ Course Num. 2 ║     10 ║
║ coco  ║ valencia       ║ Course Num. 3 ║      4 ║
║ coco  ║ valencia       ║ Course Num. 4 ║      5 ║
║ John  ║ Smith          ║ Course Num. 1 ║      7 ║
║ John  ║ Smith          ║ Course Num. 2 ║      6 ║
╚═══════╩════════════════╩═══════════════╩════════╝

我希望我的表格结果是这样的......

╔═══════╦═══════════╦══════════════╦═══════════════╦═══════════════╗
║ name  ║ last_name ║ Course Num.1 ║ Course Num. 2 ║ Course Num. 3 ║
╠═══════╬═══════════╬══════════════╬═══════════════╬═══════════════╣
║ coco  ║ valencia  ║           11 ║            10 ║             4 ║
║ John  ║ Smith     ║            7 ║             6 ║               ║
╚═══════╩═══════════╩══════════════╩═══════════════╩═══════════════╝

我一直在寻找,找不到办法。解决方案可以是 PHP 或 MySQL 或两者。

4

1 回答 1

2
SELECT  name, last_Name,
        MAX(CASE WHEN course_name = 'Course Num. 1' THEN tries ELSE NULL END) `Course Num. 1`,
        MAX(CASE WHEN course_name = 'Course Num. 2' THEN tries ELSE NULL END) `Course Num. 2`,
        MAX(CASE WHEN course_name = 'Course Num. 3' THEN tries ELSE NULL END) `Course Num. 3`
FROM    tableName
GROUP BY name, last_Name

如果你有未知数量的Course_NamePreparedStatement就是你需要的,

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN course_name =  ''',
      course_name,
      ''' then tries ELSE NULL end) AS ''',
      course_name, ''''
    )
  ) INTO @sql
FROM tableName;

SET @sql = CONCAT('SELECT  name, last_Name, ', @sql, ' 
                   FROM    tableName
                   GROUP BY name, last_Name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2012-11-27T01:55:33.630 回答