一道行列转换的查询题目

 在笔试中遇到了一道数据库行列转换的题目,题目如下:

 

假如有一个表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;

 

不知道对于上面题目有没有更好的方法,望请指教!

 

 

 

 

           

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值