行转列,列转行是我们在开发过程中经常碰到的问题。行转列一般通过CASE WHEN 语句来实现,也可以通过 SQL SERVER 2005 新增的运算符PIVOT来实现。用传统的方法,比较好理解。层次清晰,而且比较习惯。 但是PIVOT 、UNPIVOT提供的语法比一系列复杂的SELECT…CASE 语句中所指定的语法更简单、更具可读性
下面只简单介绍一下case when的方式
CREATE TABLE `student` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`user_name` varchar(100) DEFAULT NULL,
`subject` varchar(100) DEFAULT NULL,
`score` float DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO student(user_name,SUBJECT,score) VALUES('Nick','语文',80);
INSERT INTO student(user_name,SUBJECT,score) VALUES('Nick','数学',90);
INSERT INTO student(user_name,SUBJECT,score) VALUES('Nick','英语',70);
INSERT INTO student(user_name,SUBJECT,score) VALUES('Nick','生物',85);
INSERT INTO student(user_name,SUBJECT,score) VALUES('Kent','语文',80);
INSERT INTO student(user_name,SUBJECT,score) VALUES('Kent','数学',90);
INSERT INTO student(user_name,SUBJECT,score) VALUES('Kent','英语',70);
INSERT INTO student(user_name,SUBJECT,score) VALUES('Kent','生物',85);
如果我想知道每位学生的每科成绩,而且每个学生的全部成绩排成一行,这样方便我查看、统计,导出数据
SELECT
user_name,
MAX(CASE SUBJECT WHEN '语文' THEN score ELSE 0 END) AS '语文',
MAX(CASE SUBJECT WHEN '数学' THEN score ELSE 0 END) AS '数学',
MAX(CASE SUBJECT WHEN '英语' THEN score ELSE 0 END) AS '英语',
MAX(CASE SUBJECT WHEN '生物' THEN score ELSE 0 END) AS '生物'
FROM student
GROUP BY user_name;
查询结果如图所示,这样我们就能很清楚的了解每位学生所有的成绩了
其实行转列,关键是要理清逻辑,而且对分组(Group by)概念比较清晰