欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mysql动态行转列

程序员文章站 2022-05-11 15:21:33
...
测试数据
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');


行转列
动态取出需要行转列的列头
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;


用concat拼接sql放在stmt中执行
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;


这样即完成了行转列