mysql行轉(zhuǎn)列、列轉(zhuǎn)行
語(yǔ)句不難,不做多余解釋了,看語(yǔ)句時(shí),從內(nèi)往外一句一句剖析
行轉(zhuǎn)列
有如圖所示的表,現(xiàn)在希望查詢的結(jié)果將行轉(zhuǎn)成列
建表語(yǔ)句如下:
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=utf8;
insert into TEST_TB_GRADE(USER_NAME, COURSE, SCORE) values
("張三", "數(shù)學(xué)", 34),
("張三", "語(yǔ)文", 58),
("張三", "英語(yǔ)", 58),
("李四", "數(shù)學(xué)", 45),
("李四", "語(yǔ)文", 87),
("李四", "英語(yǔ)", 45),
("王五", "數(shù)學(xué)", 76),
("王五", "語(yǔ)文", 34),
("王五", "英語(yǔ)", 89);
查詢語(yǔ)句:
此處用之所以用MAX是為了將無(wú)數(shù)據(jù)的點(diǎn)設(shè)為0,防止出現(xiàn)NULL
SELECT user_name ,
MAX(CASE course WHEN '數(shù)學(xué)' THEN score ELSE 0 END ) 數(shù)學(xué),
MAX(CASE course WHEN '語(yǔ)文' THEN score ELSE 0 END ) 語(yǔ)文,
MAX(CASE course WHEN '英語(yǔ)' THEN score ELSE 0 END ) 英語(yǔ)
FROM test_tb_grade
GROUP BY USER_NAME;
結(jié)果展示:
列轉(zhuǎn)行
有如圖所示的表,現(xiàn)在希望查詢的結(jié)果將列成行
建表語(yǔ)句如下:
CREATE TABLE `TEST_TB_GRADE2` (
`ID` int(10) NOT NULL AUTO_INCREMENT,
`USER_NAME` varchar(20) DEFAULT NULL,
`CN_SCORE` float DEFAULT NULL,
`MATH_SCORE` float DEFAULT NULL,
`EN_SCORE` float DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
insert into TEST_TB_GRADE2(USER_NAME, CN_SCORE, MATH_SCORE, EN_SCORE) values
("張三", 34, 58, 58),
("李四", 45, 87, 45),
("王五", 76, 34, 89);
查詢語(yǔ)句:
select user_name, '語(yǔ)文' COURSE , CN_SCORE as SCORE from test_tb_grade2
union select user_name, '數(shù)學(xué)' COURSE, MATH_SCORE as SCORE from test_tb_grade2
union select user_name, '英語(yǔ)' COURSE, EN_SCORE as SCORE from test_tb_grade2
order by user_name,COURSE;
結(jié)果展示:
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
您可能感興趣的文章:- MySQL中將一列以逗號(hào)分隔的值行轉(zhuǎn)列的實(shí)現(xiàn)
- 當(dāng)Mysql行鎖遇到復(fù)合主鍵與多列索引詳解
- Mysql 相鄰兩行記錄某列的差值方法
- mysql指定某行或者某列的排序?qū)崿F(xiàn)方法
- mysql 列轉(zhuǎn)行,合并字段的方法(必看)
- mysql列轉(zhuǎn)行以及年月分組實(shí)例
- mysql 列轉(zhuǎn)行的技巧(分享)
- mysql 行列動(dòng)態(tài)轉(zhuǎn)換的實(shí)現(xiàn)(列聯(lián)表,交叉表)
- 數(shù)據(jù)庫(kù)實(shí)現(xiàn)行列轉(zhuǎn)換(mysql示例)
- MySQL 中行轉(zhuǎn)列的方法