在oracle的test表中插入记录
INSERT INTO test values (N'张三',N'语文',60)
INSERT INTO test values (N'李四',N'数学',70)
INSERT INTO test values (N'王五',N'英语',80)
INSERT INTO test values (N'王五',N'数学',75)
INSERT INTO test values (N'王五',N'语文',57)
INSERT INTO test values (N'李四',N'语文',80)
INSERT INTO test values (N'张三',N'英语',100)
交叉表语句的实现:
--用于:交叉表的列数是确定的
select name,sum(case subject when '数学' then source else 0 end) as '数学',
sum(case subject when '英语' then source else 0 end) as '英语',
sum(case subject when '语文' then source else 0 end) as '语文'
from test
group by name
用oracle存储过程实现
CREATE OR REPLACE PACKAGE BODY "TEST1" as
procedure sp_test(p_cursor out t_cursor)
is
sqlstr varchar2(32767);
begin
sqlstr:='select name,';
--构造字符串
for v_cur in (select distinct subject from test)
loop
sqlstr:=sqlstr||'sum(case subject when '''|| v_cur.subject ||''' then score else 0 end ) as '|| v_cur.subject ||',';
end loop;
sqlstr := substr(sqlstr,0,length(sqlstr)-1) ||' from test group by name';
open p_cursor for sqlstr;
end;
end;
INSERT INTO test values (N'张三',N'语文',60)
INSERT INTO test values (N'李四',N'数学',70)
INSERT INTO test values (N'王五',N'英语',80)
INSERT INTO test values (N'王五',N'数学',75)
INSERT INTO test values (N'王五',N'语文',57)
INSERT INTO test values (N'李四',N'语文',80)
INSERT INTO test values (N'张三',N'英语',100)
交叉表语句的实现:
--用于:交叉表的列数是确定的
select name,sum(case subject when '数学' then source else 0 end) as '数学',
sum(case subject when '英语' then source else 0 end) as '英语',
sum(case subject when '语文' then source else 0 end) as '语文'
from test
group by name
用oracle存储过程实现
CREATE OR REPLACE PACKAGE BODY "TEST1" as
procedure sp_test(p_cursor out t_cursor)
is
sqlstr varchar2(32767);
begin
sqlstr:='select name,';
--构造字符串
for v_cur in (select distinct subject from test)
loop
sqlstr:=sqlstr||'sum(case subject when '''|| v_cur.subject ||''' then score else 0 end ) as '|| v_cur.subject ||',';
end loop;
sqlstr := substr(sqlstr,0,length(sqlstr)-1) ||' from test group by name';
open p_cursor for sqlstr;
end;
end;