行转列
创建`text_`表
CREATE TABLE `text_`(
id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
usename VARCHAR(20) DEFAULT NULL,
course VARCHAR(20) DEFAULT NULL,
score FLOAT DEFAULT '0'
)
向表中添加数据:
INSERT INTO text_ (usename,course,score) VALUES
('张三','语文',65),
("张三", "语文", 58),
("张三", "英语", 58),
("李四", "数学", 45),
("李四", "语文", 87),
("李四", "英语", 45),
("王五", "数学", 76),
("王五", "语文", 34),
("王五", "英语", 89);
SELECT user_name ,
MAX(CASE course WHEN '数学' THEN score ELSE 0 END ) 数学,
MAX(CASE course WHEN '语文' THEN score ELSE 0 END ) 语文,
MAX(CASE course WHEN '英语' THEN score ELSE 0 END ) 英语
FROM test_tb_grade
GROUP BY USER_NAME;
结果:
MySQL中 case when then else end的用法
解释:
select
case ...... #如果
when sex=1 then '男'...... #当sex='1'返回 男
when sex=2 then '女'...... #当sex='2'返回 女
else 0 ......#其它的返回其他
end ........ #结束
from text
#整体解释:在text表中如果 sex='1' 则返回值为男 sex='2' 则返回值为女,否则返回其他
列转行
创建 test_1表
CREATE TABLE `test_1` (
`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`)
)
向表中添加数据
insert into TEST_TB_GRADE2(USER_NAME, CN_SCORE, MATH_SCORE, EN_SCORE) values
("张三", 34, 58, 58),
("李四", 45, 87, 45),
("王五", 76, 34, 89);
select user_name, '语文' COURSE , CN_SCORE as SCORE from test_tb_grade2
union select user_name, '数学' COURSE, MATH_SCORE as SCORE from test_tb_grade2
union select user_name, '英语' COURSE, EN_SCORE as SCORE from test_tb_grade2
order by user_name,COURSE;