create or replace function fun_test(p_stu varchar2) return varchar2 as
cursor c is select to_char(a.grade) from table a where a.student=p_stu;
p_out varchar2(3000);
p_temp varchar2(20);
begin
open c ;
loop
fetch c into p_temp;
exit when c%notfound;
p_out:=p_out||' '||p_temp;
end loop;
close c;
return p_out;
exception
when others then
return '出错';
end
select b.student,fun_test(b.student) from ( select distinct a.student student from table a ) b
cursor c is select to_char(a.grade) from table a where a.student=p_stu;
p_out varchar2(3000);
p_temp varchar2(20);
begin
open c ;
loop
fetch c into p_temp;
exit when c%notfound;
p_out:=p_out||' '||p_temp;
end loop;
close c;
return p_out;
exception
when others then
return '出错';
end
select b.student,fun_test(b.student) from ( select distinct a.student student from table a ) b
student1 80 70 60
student2 90 75 80 100 62
student3 50 35 转换成为上边的形式:可以按照dinya2003所说的,其结果是两列数据,第一列为:student#,第二列为:gradeLIST串!按照你的要求就需要动态的进行构造SQL了!其列数是由STUDENT的GRADE个数最大的那个数值再加上一个STUDENT列构成.其中的每个grade的计算要使用一个自定义函数来得到!由于你的列的不确定性!
构成的SQL如:select student ,f_getgrade(student,1),f_getgrade(student,2),f_getgrade(student,3),......,f_getgrade(student,n) from tablename这个SQL可以使用存储过程或其他的程序按照你的数据表中的数据进行构造.其中的n是由你的表中数据决定的!
f_getgrade(参数1,参数2)该函数是自己定义的提取某一个
student的第“参数2”个的grade。此方法虽然麻烦,但是绝对可以解决你的问题!
//建立函数
CREATE OR REPLACE FUNCTION get_grade( std VARCHAR2,ordnum NUMBER)
RETURN NUMBER
IS
ret NUMBER;
BEGIN
ret :=0;
BEGIN
SELECT grade INTO ret FROM hy_student_view
WHERE student=std AND ord_num=ordnum;
EXCEPTION
WHEN OTHERS THEN
ret := 0;
END;
RETURN (ret);
END;
========================
//建两个view
CREATE OR REPLACE VIEW hy_student_view
AS
SELECT a.student,a.grade,
(select count(*) from hy_student b where b.student=a.student and a.grade>=b.grade) AS ord_num
FROM hy_student a
ORDER BY a.student,a.grade
==================================
CREATE OR REPLACE VIEW hy_student_std_view
AS
SELECT DISTINCT student FROM hy_student
=================================
//测试
SELECT student
,get_grade(student,1) s1
,get_grade(student,2) s2
,get_grade(student,3) s3
,get_grade(student,4) s4
,get_grade(student,5) s5
,get_grade(student,6) s6
FROM hy_student_std_view
//你可根据具体情况生成你想要的列数.我想你的列数应该是有限的吧.如果是无限的那还是另想法办了(暂时没想到) 留言太長回復不了你.
select fun(stuid,1) as s1
....
....
from tablename
因为你得列数不定
我想只有先通过
select student,count(student) from stu group by student;
按照最大的值建立表 列数后才能
在来选择插入吧
假如你的一个student行数有可能大于255,那么你该怎么办?
所以,我觉得你可以估计有多少列来解决.
不知你的表用途是什么?是否存的是学生的每学科成绩.如果是就做50列也足够了吧.
SELECT student
,get_grade(student,1) s1
,get_grade(student,2) s2
,get_grade(student,3) s3
,get_grade(student,4) s4
,get_grade(student,5) s5
,get_grade(student,6) s6
.....
...
.........
,get_grade(student,50) s50 FROM hy_student_std_view
======================================
假如你偏要动态的生成不固定列数.那么可以考虑
用sql动态的生成sql.
等我写好再贴给你吧.
清风!
------
另外问下,oracle 支持嵌套循环吗?
qgbin, 数据库中得到