The database column switch, turn the column row
Create a table
# 建表语句 CREATE TABLE `TEST_TB_GRADE` ( `ID` int(10) NOT NULL AUTO_INCREMENT, `USER_NAME` varchar(20) DEFAULT NULL, `COURSE` varchar(20) DEFAULT NULL, `SCORE` float DEFAULT '0', PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET= Utfa8;
adding data
# Add data INSERT INTO TEST_TB_GRADE ( USER_NAME , COURSE, SCORE) values ( "Joe Smith", "Mathematics", 34 ), ( "Joe Smith", "Chinese", 58 ), ( "Joe Smith", "English" 58 ), ( "John Doe", "Mathematics", 45 ), ( "John Doe", "Chinese", 87 ), ( "John Doe", "English", 45 ), ( "Wang five", "math " 76 ), (" Wang five "," Chinese ", 34 ), (" Wang five "," English ", 89 );
SQL column switch
# Column switch the SELECT user_name , MAX ( the CASE Course, the WHEN ' mathematics ' THEN Score ELSE 0 END ) mathematics, MAX ( the CASE Course, the WHEN ' language ' THEN Score ELSE 0 END ) language, MAX ( the CASE Course, the WHEN ' English ' THEN Score ELSE 0 END ) English the FROM test_tb_grade the GROUP BY USER_NAME;
Column switch changes
Line transfer column
Need to first convert the data into the result table result
Results Table # Create a table the CREATE TABLE `result` ( ` USER_NAME ` VARCHAR ( 20 is ) the DEFAULT NULL , ` COURSE` VARCHAR ( 20 is ) the DEFAULT NULL , `SCORE` a float the DEFAULT ' 0 ' ) ENGINE = the InnoDB the AUTO_INCREMENT = . 1 the DEFAULT the CHARSET = UTF8 ; # query results to the data transferred to the table INSERT iNTO result the SELECT USER_NAME , MAX (The CASE Course, the WHEN ' mathematics ' THEN Score ELSE 0 END ) mathematics, MAX ( the CASE Course, the WHEN ' language ' THEN Score ELSE 0 END ) language, MAX ( the CASE Course, the WHEN ' English ' THEN Score ELSE 0 END ) English the FROM test_tb_grade the GROUP BY USER_NAME ;
After then turn the column row
# Line switch columns the SELECT USER_NAME , ' language ' COURSE, MAX (language) AS Score from the Result the GROUP by USER_NAME of Union ALL the SELECT USER_NAME , ' mathematics ' COURSE, MAX (mathematics) AS Score from the Result the GROUP by USER_NAME of Union ALL the SELECT USER_NAME , ' English ' COURSE, MAX (English) AS Score from result GROUP by USER_NAME
Changes turn row columns