SQL语句行列转换
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL语句行列转换相关的知识,希望对你有一定的参考价值。
创建表格
CREATE TABLE T2 (STU_NAME CHAR(5),COURSE CHAR(5),MARK INT NOT NULL) INSERT INTO T2 VALUES (‘城南‘,‘马哲‘,70) INSERT INTO T2 VALUES (‘城南‘,‘数学‘,65) INSERT INTO T2 VALUES (‘城南‘,‘英语‘,58) INSERT INTO T2 VALUES (‘城南‘,‘语文‘,79) INSERT INTO T2 VALUES (‘李四‘,‘马哲‘,61) INSERT INTO T2 VALUES (‘李四‘,‘数学‘,80) INSERT INTO T2 VALUES (‘李四‘,‘英语‘,77) INSERT INTO T2 VALUES (‘李四‘,‘语文‘,80) INSERT INTO T2 VALUES (‘王朝‘,‘马哲‘,52) INSERT INTO T2 VALUES (‘王朝‘,‘数学‘,55) INSERT INTO T2 VALUES (‘王朝‘,‘英语‘,59) INSERT INTO T2 VALUES (‘王朝‘,‘语文‘,90) INSERT INTO T2 VALUES (‘张三‘,‘马哲‘,66) INSERT INTO T2 VALUES (‘张三‘,‘数学‘,88) INSERT INTO T2 VALUES (‘张三‘,‘英语‘,61) INSERT INTO T2 VALUES (‘张三‘,‘语文‘,70)
生成如下图表--
要求换列生成如下表格
方法一
select stu_name, max(case course when ‘马哲‘ then mark else 0 end) as ‘马哲‘, max(case course when ‘数学‘ then mark else 0 end) as ‘数学‘, max(case course when ‘英语‘ then mark else 0 end) as ‘英语‘, max(case course when ‘语文‘ then mark else 0 end) as ‘语文‘ from t2 group by stu_name order by stu_name
方法二
SELECT A.STU_NAME AS ‘姓名‘, A.MARK AS ‘马哲‘, B.MARK AS ‘数学‘, C.MARK AS ‘英语‘, D.MARK AS ‘语文‘ FROM T2 AS A --把分数那列别名 INNER JOIN T2 AS B ON A.STU_NAME=B.STU_NAME INNER JOIN T2 AS C ON B.STU_NAME=C.STU_NAME INNER JOIN T2 AS D ON C.STU_NAME=D.STU_NAME WHERE A.COURSE=‘马哲‘ AND B.COURSE=‘数学‘ AND C.COURSE=‘英语‘ AND D.COURSE=‘语文‘
方法三
--group by, avg/max, pivot。这里用max和avg,结果都一样,有什么区别吗?有点不明白 --参考网上的资料,用法如下 /* pivot( 聚合函数(要转成列值的列名) for 要转换的列 in(目标列名) ) */ select stu_name as ‘姓名‘, avg(语文) as ‘马哲‘, avg(数学) as ‘数学‘, avg(英语) as ‘英语‘, avg(语文) as ‘语文‘ from T2 pivot( avg(MARK) for course in (马哲,数学,英语,语文) )as NewScores group by stu_name order by stu_name asc
--优化为 SELECT STU_NAME AS ‘姓名‘, [马哲],[数学],[英语],[语文] FROM T2 PIVOT( MAX(MARK) FOR COURSE IN ([马哲],[数学],[英语],[语文])--以值变列,平均每个课程下的分数变成列 ) AS NEW--一定要别名,否则报错
没有根据学生分类也会自动成功???
以上是关于SQL语句行列转换的主要内容,如果未能解决你的问题,请参考以下文章