如何为动态生成的列添加摘要行?

时间:2015-10-24 16:03:53

标签: mysql aggregate-functions pivot-table

我有两张桌子,非常像in this question

但我不仅要创建一个动态生成列的数据透视表,还要获得每列总计的摘要行。也就是说,给定this tables,我的数据透视表应如下所示:

╔══════════════╦══════════════╦══════════════╗
║ STUDENT_NAME ║ ITEM_1_SCORE ║ ITEM_2_SCORE ║
╠══════════════╬══════════════╬══════════════╣
║ dan          ║         55   ║         44   ║
║ david        ║         66   ║         45   ║
║ jon          ║         37   ║         45   ║
╠══════════════╬══════════════╬══════════════╣
║SUM           ║       158    ║        134   ║

我尝试了这个解决方案(它本身很好用):

SELECT  GROUP_CONCAT(DISTINCT
        CONCAT('MAX(CASE WHEN item_id = ''',
               item_id,
               ''' THEN Score END) AS ',
               CONCAT('`Item_', item_id, '_Score`')
               )) INTO @sql
FROM scores;

SET @sql = CONCAT('SELECT   a.Name AS Student_Name, ', @sql, ' 
                    FROM    student_info a
                            LEFT JOIN scores b
                                ON a.id = b.student_ID
                    GROUP   BY a.Name');

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

WITH ROLLUP的加法给出了最大值,而不是总和。我也尝试过使用

(SELECT ...) UNION (SELECT "SUM" as Student_Name, SUM(Score) as Item1 ...etc

但它仅适用于预定义的固定数量的列。

感谢您的帮助。

0 个答案:

没有答案