使用游标实现Oracle中的行列转换

来源:互联网 发布:启辰网络 编辑:程序博客网 时间:2024/06/05 00:24

游标是SQL语句中非常实用的一个工具

这里我们使用游标实现行列转换


何为行列转换呢


比如 原来有一张表是这样的:




我们要实现这样的效果


这里就可以利用游标来实现我们的行列转换了


首先我们在PL/SQL中创建一张表

create table tb (t_name varchar2(10),t_course varchar2(10), t_score number);
insert into tb values('张三','语文',73);
insert into tb values('张三','数学',93);
insert into tb values('张三','英语',53);
insert into tb values('李四','语文',96);
insert into tb values('李四','数学',75);
insert into tb values('李四','英语',87);


然后我们使用游标辅助来实现行列转换

declare
 t_name varchar2(10);
 t_course1 number;
 t_course2 number;
 t_course3 number;
 type c_type is ref cursor;——声明游标类型
 cur c_type;  ——定义游标
 
begin
  open cur for
  'select t_name ,
   sum(case t_course when '''||'语文'||'''then t_score else 0 end),           ——这里我们使用了sum函数表示统计每一列
   sum(case t_course when '''||'数学'||'''then t_score else 0 end),  
   sum(case t_course when '''||'英语'||'''then t_score else 0 end)
   from tb group by t_name' ;

 
  loop
    fetch cur into t_name,t_course1,t_course2,t_course3;  --循环提取游标信息
    exit when cur%notfound; ——Loop结束条件设置
    dbms_output.put_line(
    t_name||'语文'||t_course1||'数学'||t_course2||'英语'||t_course3);
 end loop;
  close cur;
end;



原创粉丝点击