我希望转换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
感谢您的帮助
答案 0 :(得分:9)
静态查询(仅涉及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 演示
答案 1 :(得分:0)
为转换编写存储过程。
SELECT DISTINCT name FROM table1;
获取Pivot_table的列列表。为主题创建具有适当列数+ 1的表。
在数据透视表中插入所有主题,为每个主题获取1行。 INSERT ... from SELECT DISTINCT subject FROM table1
。
创建游标以从table1中检索所有记录。遍历游标的所有行,并为每行调用UPDATE Pivot_table SET [COLUMN_NAME for studetn value]=[grade value] WHERE subject=[subject name value];