我希望转换Table1中的数据,如Pivot_table中数据的第一张图片所示.有可能在MySQL中这样做吗?因为数据透视表(A,B,C,D)的值是varchar数据格式,我不能像SUM那样使用MySQL的任何聚合函数.
Table1:
PK Name Subject Grade
-------------------------------------
1 Bob Math A
2 Bob History B
3 Bob Language C
4 Bob Biology D
5 Sue History C
6 Sue Math A
7 Sue Music A
8 Sue Geography C
Pivot_table:
Subject Bob Sue
-------------------------
Math A A
History B C
Language C
Biology D
Music A
Geography C
谢谢你的帮助
解决方法:
静态查询(仅涉及Bob和Sue)可能如下所示
SELECT subject,
MAX(CASE WHEN name = 'Bob' THEN grade END) `Bob`,
MAX(CASE WHEN name = 'Sue' THEN grade END) `Sue`
FROM table1
GROUP BY subject
现在能够考虑其他名称使用像这样的动态SQL
SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE WHEN name = ''', name,
''' THEN grade END) `', name, '`'))
INTO @sql
FROM table1;
SET @sql = CONCAT('SELECT subject, ', @sql, '
FROM table1
GROUP BY subject');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
输出:
| SUBJECT | BOB | SUE | |-----------|--------|--------| | Biology | D | (null) | | Geography | (null) | C | | History | B | C | | Language | C | (null) | | Math | A | A | | Music | (null) | A |
这是SQLFiddle演示
您可以将其包装到存储过程中以简化调用端的操作
DELIMITER $$
CREATE PROCEDURE sp_grade_report()
BEGIN
SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE WHEN name = ''', name,
''' THEN grade END) `', name, '`'))
INTO @sql
FROM table1;
SET @sql = CONCAT('SELECT subject, ', @sql, '
FROM table1
GROUP BY subject');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
样品用法:
CALL sp_grade_report();
这是SQLFiddle演示