1、科目成绩与学生成绩转换问题
上述两种数据表现形式如何在ORACLE中互相转换?
2、oracle中的model子句
在使用前请大家看一下oracle中的model子句相关介绍传送门
3、基本表结构
为了让大家可以更明白看两者之间如何转换,两种表结构我们各建一个并插入数据
-- 科目成绩表
create table t_subject_score(
student_name varchar2(20),
subject varchar2(20),
score number
);
-- 学生成绩表
create table t_student_score(
student_name varchar2(20),
chinese_score number,
math_score number,
english_score number,
sport_score number
);
-- 插入原始数据
insert into t_subject_score values ('A', 'chinese', 60);
insert into t_subject_score values ('A', 'math', 100);
insert into t_subject_score values ('A', 'english', 70);
insert into t_subject_score values ('A', 'sport', 75);
insert into t_subject_score values ('B', 'chinese', 95);
insert into t_subject_score values ('B', 'math', 90);
insert into t_subject_score values ('B', 'english', 90);
insert into t_subject_score values ('B', 'sport', 50);
insert into t_student_score values ('A', 60, 100, 70, 75);
insert into t_student_score values ('B', 95, 90, 90, 50);
4、行列转换方法
科目成绩转换成学生成绩相对简单很多,大家相关使用经验也更丰富,在此不过多赘述
-- 科目成绩表 --> 学生成绩表
select student_name,
max(case when subject = 'chinese' then score end) chinese_score,
max(case when subject = 'math' then score end) math_score,
max(case when subject = 'english' then score end) english_score,
max(case when subject = 'sport' then score end) sport_score
from t_subject_score group by student_name;
学生成绩转换成科目成绩需要使用model子句,通过【内容2】相信大家对model子句已经有了基础的了解,下面先列出转换SQL
-- 学生成绩表 --> 科目成绩表
select student_name, subject, score from
(select student_name,
chinese_score,
math_score,
english_score,
sport_score,
'1111111111111' subject,
0 score
from t_student_score)
model return updated rows
partition by (student_name)
dimension by (subject)
measures(score, chinese_score, math_score, english_score, sport_score)
rules
(
score['chinese'] = chinese_score['1111111111111'],
score['math'] = math_score['1111111111111'],
score['english'] = english_score['1111111111111'],
score['sport'] = sport_score['1111111111111']
);
需要说明的一些地方
【1】subject、score数据类型要根据实际功能需要来调整,比如score字段在实际功能中需要为varchar2类型,则应调整为‘’形式,并根据内容需要来填充字段大小
【2】return updated rows为非必须项,有就只显示根据规则修改的内容,否则会显示原表+修改过的内容
5、进击的巨人
model子句功能强大,使用方法也非常多,大家有兴趣可以参考下另外一篇文章,比较详细的讲述了一些高级用法传送门
6、其它
如需转载,请注明源自流氓你怕谁,或直接引入本BLOG链接