首页 > 数据库技术 > 详细

SQL行转列

时间:2019-05-16 23:41:15      阅读:207      评论:0      收藏:0      [点我收藏+]

1.行转列

1.经典案例:

新建一个数据表

create table STUDENT_SCORE
(
name VARCHAR2(20),
subject VARCHAR2(20),
score NUMBER(4,1)
)
insert into student_score (NAME, SUBJECT, SCORE) values (‘张三‘, ‘语文‘, 78.0);
insert into student_score (NAME, SUBJECT, SCORE) values (‘张三‘, ‘数学‘, 88.0);
insert into student_score (NAME, SUBJECT, SCORE) values (‘张三‘, ‘英语‘, 98.0);
insert into student_score (NAME, SUBJECT, SCORE) values (‘李四‘, ‘语文‘, 89.0);
insert into student_score (NAME, SUBJECT, SCORE) values (‘李四‘, ‘数学‘, 76.0);
insert into student_score (NAME, SUBJECT, SCORE) values (‘李四‘, ‘英语‘, 90.0);
insert into student_score (NAME, SUBJECT, SCORE) values (‘王五‘, ‘语文‘, 99.0);
insert into student_score (NAME, SUBJECT, SCORE) values (‘王五‘, ‘数学‘, 66.0);
insert into student_score (NAME, SUBJECT, SCORE) values (‘王五‘, ‘英语‘, 91.0);

得到类似下面的结果:
姓名 语文 数学 英语
王五 89 56 89

 

select ts.name,

sum(decode(ts.subject,‘语文‘,ts.score)) "语文",

sum(decode(ts.subject,‘数学‘,ts.score)) "数学",

sum(decode(ts.subject,‘英语‘,ts.score)) "英语"

from test_score ts

group by ts.name

SQL行转列

原文:https://www.cnblogs.com/abcdjava/p/10878793.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!