DROP TABLE IF EXISTS `score`; CREATE TABLE `score` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `class` VARCHAR(255) DEFAULT NULL, `score` DOUBLE DEFAULT NULL, `userid` INT(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=INNODB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; INSERT INTO `score` VALUES ('1', 'math', '90', '1'); INSERT INTO `score` VALUES ('2', 'english', '90', '1'); INSERT INTO `score` VALUES ('3', 'computer', '80', '1'); INSERT INTO `score` VALUES ('4', 'sports', '90', '1'); INSERT INTO `score` VALUES ('5', 'math', '80', '2'); INSERT INTO `score` VALUES ('6', 'english', '85', '2'); INSERT INTO `score` VALUES ('7', 'computer', '100', '2');
Rows to columns
Dynamically remove the column headers that need to be row-to-column
SET @ EE = ''; SET @str_tmp=''; SELECT @EE:=CONCAT(@EE,'SUM(IF(class=\'',class,'\'',',score,0)) AS ',class,',') AS aa INTO @str_tmp FROM (SELECT DISTINCT class FROM score) A ORDER BY LENGTH(aa) DESC LIMIT 1;
Use concat to splice sql and put it in stmt for execution
SET @QQ=CONCAT('SELECT ifnull(score.userid,\'total\'),',LEFT(@str_tmp,CHAR_LENGTH(@str_tmp)-1),' ,SUM(score) AS TOTAL FROM score GROUP BY userid WITH ROLLUP'); PREPARE stmt FROM @QQ; EXECUTE stmt ; DEALLOCATE PREPARE stmt;
This completes the row to column