Oracle实现行转换成列的方法

本文实例讲述了Oracle实现行转换成列的方法。分享给大家供大家参考,具体如下:

把行转成列 把学生表,成绩表,班级表,学科表 合并成一张成绩表效果如下:

创建表

–班级表
create table CLASS
(
ID VARCHAR2(5) not null primary key,
CLASSNAME VARCHAR2(10)
);
–学生表
create table STUDENT
(
ID VARCHAR2(10) not null primary key,
NAME VARCHAR2(10),
AGE NUMBER(3),
CLASSID VARCHAR2(5)
);
–科目表
create table subject(
id varchar2(10) primary key,
subname varchar2(10)
);
–分数表
create table score(
sid varchar2(4),
subid varchar2(10),
score number(4,1)
);

查询sql 如下

select s1.name 姓名,
s1.age 年龄,
s1.classname 班级,
score_.sid,
数学,
语文,
物理,
化学,
(数学 + 语文 + 物理 + 化学) 总分
from (select s.sid,
sum(decode(s.subid, ‘SUB001’, s.score)) 数学,
sum(decode(s.subid, ‘SUB002’, s.score)) 语文,
sum(decode(s.subid, ‘SUB003′, s.score)) 物理,
sum(decode(s.subid,’SUB004’,s.score)) 化学
from score s
group by s.sid) score_
right join (select st.id, st.name, st.age, c.classname
from student st, class c
where c.id = st.classid) s1 on s1.id = score_.sid
order by 总分;

更多关于Oracle相关内容感兴趣的读者可查看本站专题:《php+Oracle数据库程序设计技巧总结

希望本文所述对大家Oracle数据库程序设计有所帮助。


数据运维技术 » Oracle实现行转换成列的方法