行轉列後的資料:
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;