在笔试中遇到了一道数据库行列转换的题目,题目如下:
假如有一个表test结构如下:
test表:
COL1 COL2
---------- ----------
a aaa1
b bbb1
a aaa2
b bbb2
a aaa3
a aaa4
c ccc1
要求查询结果为:
a aaa1 aaa2 aaa3 aaa4
b bbb1 bbb2
c ccc1
我使用了一种比较笨的方法实现了,不知道看见这文章的朋友有没有更好的方法留下!
我的方法:
declare
new_col2 varchar2(4000);
begin
for curr in(select distinct col1 from test) loop
new_col2:='';
for cur in(select col2 from test where col1=curr.col1) loop
new_col2:=new_col2||' '||cur.col2;
end loop;
dbms_output.put_line(curr.col1||' '||rtrim(new_col2));
end loop;
end;
结果为:
a aaa1 aaa2 aaa3 aaa4
b bbb1 bbb2
c ccc1
【08年12月13日更新】学习中发现可以使用sys_connect_by_path函数和start with...connect by prior子句 来实现行列转换:
--->> http://blog.youkuaiyun.com/echoetang/archive/2008/12/13/3510715.aspx
从这道题我联想到另外一道:
有一个表grades:
STUDENT SUBJECT GRADE
--------------- --------------- ----------
student1 语文 80
student1 数学 79
student1 英语 95
student2 语文 70
student2 数学 88
student2 英语 91
student3 英语 75
student3 数学 80
student3 语文 86
要求实现查询结果:
学生 语文 数学 英语
--------------- ---------- ---------- ----------
student1 80 79 95
student2 70 88 91
student3 86 80 75
我的方法是:
select student 学生,sum(decode(subject,'语文',grade,null)) 语文,sum(decode(subject,'数学',grade,null)) 数学,sum(decode(subject,'英语',grade,null)) 英语
from grades
group by student;
不知道对于上面题目有没有更好的方法,望请指教!