1. 程式人生 > >mysql一維轉二維資料

mysql一維轉二維資料

例子資料

DROP TABLE IF EXISTS tmp0103.temp_test;
CREATE TABLE tmp0103.temp_test (
  `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 tmp0103.temp_test VALUES ('1', 'math', '90', '1');
INSERT INTO tmp0103.temp_test VALUES ('2', 'english', '90', '1');
INSERT INTO tmp0103.temp_test VALUES ('3', 'computer', '80', '1');
INSERT INTO tmp0103.temp_test VALUES ('4', 'sports', '90', '1');
INSERT INTO tmp0103.temp_test VALUES ('5', 'math', '80', '2');
INSERT INTO tmp0103.temp_test VALUES ('6', 'english', '85', '2');
INSERT INTO tmp0103.temp_test VALUES ('7', 'computer', '100', '2');

通過定義變數儲存臨時結果

/*以下如果在mysql客戶端,需要一條一條執行*/
SET @EE='';  /*定義變數EE為空*/
    SELECT @EE:=CONCAT(@EE,'SUM(IF(class=\'',class,'\'',',score,0)) AS ',class,',')   
    FROM (SELECT DISTINCT class FROM tmp0103.temp_test) A;  /*\'為在引號裡面的\是對'的轉義*/
SET @QQ=CONCAT('SELECT tmp0103.temp_test.userid AS columnA,',LEFT(@EE,LENGTH(@EE)-1),'   
    FROM tmp0103.temp_test GROUP BY userid');  /*LEFT(@EE,LENGTH(@EE)-1),去掉EE中最後一句的最後一個,*/
PREPARE stmt2 FROM @QQ; /*預處理需要執行的動態SQL,其中stmt是一個變數*/
execute stmt2;  /*執行SQL語句*/
deallocate prepare stmt;  /*釋放掉預處理段*/