-- 创建表
CREATE TABLE `col_to_row` (
`ID` int(10) AUTO_INCREMENT,
`USER_NAME` varchar(20) DEFAULT NULL,
`COURSE` varchar(20) DEFAULT NULL,
`SCORE` float DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
-- 插入数据
INSERT INTO col_to_row (user_name,course,score)values('张三', '语文', 58);
INSERT INTO col_to_row (user_name,course,score)values('张三', '数学', 34);
INSERT INTO col_to_row (user_name,course,score)values('张三', '英语', 58);
INSERT INTO col_to_row (user_name,course,score)values('李四', '语文', 87);
INSERT INTO col_to_row (user_name,course,score)values('李四', '数学', 45);
INSERT INTO col_to_row (user_name,course,score)values('李四', '英语', 45);
INSERT INTO col_to_row (user_name,course,score)values('王五', '语文', 34);
INSERT INTO col_to_row (user_name,course,score)values('王五', '数学', 76);
INSERT INTO col_to_row (user_name,course,score)values('王五', '英语', 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 col_to_row
GROUP BY user_name;
MAX的作用 当我们执行如下代码时 未加MAX
SELECT
user_name,
(CASE course WHEN '数学' THEN score else 0 end) as 数学,
(CASE course WHEN '语文' THEN score else 0 end) as 语文,
(CASE course WHEN '英语' THEN score else 0 end) as 英语
FROM col_to_row ;
结果如下:
当添加MAX后
实际上MAX可以换成其他一些聚合函数如MIN
--方法二
SELECT
user_name,
(SELECT score FROM col_to_row b WHERE course='数学' AND a.user_name = b.user_name) as 数学,
(SELECT score FROM col_to_row b WHERE course='语文' AND a.user_name = b.user_name) as 语文,
(SELECT score FROM col_to_row b WHERE course='英语' AND a.user_name = b.user_name) as 英语
FROM col_to_row a GROUP BY user_name;