Mysql动态行转列(不使用存储过程)
数据:
行转列后的数据:
SQL如下(示例):
创建表格
CREATE TABLE `dome` (
`id` INT NOT NULL AUTO_INCREMENT,
`testdate` DATE DEFAULT NULL COMMENT '时间',
`testtext` VARCHAR(50) DEFAULT NULL COMMENT '姓名',
`stature` DOUBLE DEFAULT NULL COMMENT '身高',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
数据
>INSERT INTO `dome`(`id`,`testdate`,`testtext`,`stature`)
>VALUES (5,'2020-10-01','张三',1.66),
>(6,'2020-11-01','张三',1.68),
>(7,'2020-12-01','张三',1.7),
>(8,'2020-10-01','李四',1.7),
>(9,'2020-11-01','李四',1.76),
>(10,'2020-12-01','李四',1.78),
>(11,'2020-10-01','王五',1.66),
>(12,'2020-11-01','王五',1.7),
>(13,'2020-12-01','王五',1.75);
行转列动态SQL
SET @sql = NULL;
SELECt
GROUP_CONCAT(DISTINCT
CONCAT( 'sum(IF(a.testdate = ''', DATE_FORMAT(a.testdate, '%Y-%m-%d'), ''', a.stature, 0)) AS ''', DATE_FORMAT(a.testdate,'%Y-%m-%d'), ''''
)
) INTO @sql
FROM (SELECt * FROM dome WHERe testdate BETWEEN '2020-10-01' AND '2020-12-20') a;
SET @sql = CONCAT('Select testtext,', @sql, ' From dome a Group by a.testtext' );
PREPARE stmt FROM @sql; -- 动态生成脚本
EXECUTE stmt; -- 动态执行脚本
DEALLOCATE PREPARE stmt;
PREPARE stmt2 FROM @sql; -- 生产sql
EXECUTE stmt2; -- 执行sql
SELECT @sql --可查看生成的sql
注意:数据量大的时候group_concat有长度限制!默认1024
执行如下SQL改变group_concat长度
SET GLOBAL group_concat_max_len=102400;
SET SESSION group_concat_max_len=102400;