行转列的4种方法(有完整例)

1.0
有两个表,例如:
table1:
姓名性别年龄
张三男22
李四男19
table2:
姓名科目成绩
张三数学88
张三语文78
李四数学79
李四语文91
我想查询的结果是这样的
姓名数学语文
张三8878
李四7991
===========
(1)select a.姓名,sum(decode(b.科目,'数学',成绩) as 数学,
sum(decode(b.科目,'语文',成绩) as 语文
from table1 a,table2 b where a.姓名=b.姓名
group by a.姓名
(2)declare v_sql varchar2(4000):='select a.姓名,';
cursor cur_name is select distinct 科目 from table2;
begin
for c in cur_name loop
v_sql:=v_sql||'max(decode(b.科目,'||c.科目||',b.成绩))'''||c.科目||''',';
end loop;
v_sql:=substr(v_sql,1,length(v_sql)-1)||' from table1 a,table2 b where a.姓名=b.姓名
group by a.姓名';
execute immediate v_sql;
(3)create table table1( cname varchar2(100),csex varchar2(100),cage int )
insert into table1
select '张三','男',22 from dual
union
select '李四','男',19 from dual;

create table table2(cname varchar2(100),km varchar2(100),cj int )
insert into table2
select '张三','数学',88 from dual
union
select '张三','语文',78 from dual
union
select '李四','数学',79 from dual
union
select '李四','语文',91 from dual;
==
select
a.cname,
max(decode(b.km,'数学',b.cj)) as 数学,
max(decode(b.km,'语文',b.cj)) as 语文
from
table1 a,table2 b
where
a.cname=b.cname
group by
a.cname
【行转列的4种方法(有完整例)】(4)selecta.stu_name,
(select b.stu_scorefrom dev.table2 b where b.stu_name=a.stu_name and b.stu_course='数学') math,
(select b.stu_scorefrom dev.table2 b where b.stu_name=a.stu_name and b.stu_course='语文') chinese
from dev.table1 a

    推荐阅读