上一章我们讲了固定行转列,本章我们就将一下怎么动态实现行转列的。因为有时候需要行专列的值有成千上万条,不可能再用固定行转列的方法,否则你一定会崩溃掉的。好了,废话不多说,开始吧!
常见一张表tmp_test,内容如下:
实现代码:
create or replace procedure p_test is
v_sql varchar2(2000);
cursor cursor_1 is
select distinct subject from tmp_test order by subject;
begin
v_sql := ‘select username‘;
for v_subject in cursor_1 loop
v_sql := v_sql || ‘,‘ ||‘sum(decode(subject,‘‘‘ ||v_subject.subject ||‘‘‘,source)) as ‘ ||v_subject.subject;
dbms_output.put_line(v_sql);
end loop;
v_sql := vql || ‘ from tmp_test group by username‘;
dbms_output.put_line(v_sql);
v_sql := ‘create or replace view test_result as ‘ || v_sql;
execute immediate v_sql;
end;
存储过程已经写好了,开始调用存过:
begin
p_test;
end;
查询视图test_result:
代码实现:
select * from test_result;
数据如下:
到这一步,动态行转列就已经实现了!希望对小伙伴有帮助!
原文地址:https://blog.51cto.com/12777507/2404745