日期:2014-05-17 浏览次数:20968 次
create or replace procedure row_to_col(tabname in varchar2, group_col in varchar2, column_col in varchar2, value_col in varchar2, Aggregate_func in varchar2 default 'max', colorder in varchar2 default null, roworder in varchar2 default null, when_value_null in varchar2 default null, viewname in varchar2 default 'v_tmp') Authid Current_User as sqlstr varchar2(2000):='create or replace view '||viewname||' as select '||group_col||' '; c1 sys_refcursor; v1 varchar2(100); begin open c1 for 'select distinct '||column_col||' from '||tabname||case when colorder is not null then ' order by '||colorder end; loop fetch c1 into v1; exit when c1%notfound; sqlstr:=sqlstr||chr(10)||','||case when when_value_null is not null then 'nvl(' end|| Aggregate_func||'(decode(to_char('||column_col||'),'''||v1||''','||value_col||'))'|| case when when_value_null is not null then chr(44) ||when_value_null||chr(41) end||'"'||v1||'"'; end loop; close c1; sqlstr:=sqlstr||' from '||tabname||' group by '||group_col||case when roworder is not null then ' order by '||roworder end; execute immediate sqlstr; end row_to_col;
--测试数据 create table rowtocol_test as select 2009 year,1 month,'部门1' dept,50000 expenditure from dual union all select 2009,2,'部门1',20000 from dual union all select 2009,2,'部门1',30000 from dual union all select 2010,1,'部门1',35000 from dual union all select 2009,2,'部门2',40000 from dual union all select 2009,3,'部门2',25000 from dual union all select 2010,2,'部门3',60000 from dual union all select 2009,2,'部门3',15000 from dual union all select 2009,2,'部门3',10000 from dual;
SQL> select * from rowtocol_test; YEAR MONTH DEPT EXPENDITURE ---------- ---------- ----- ----------- 2009 1 部门1 50000 2009 2 部门1 20000 2009 2 部门1 30000 2010 1 部门1 35000 2009 2 部门2 40000 2009 3 部门2 25000 2010 2 部门3 60000 2009 2 部门3 15000 2009 2 部门3 10000 9 rows selected SQL> execute row_to_col('rowtocol_test','year,month','dept','expenditure'); PL/SQL procedure successfully completed SQL> select * from v_tmp; YEAR MONTH 部门1 部门3 部门2 ---------- ---------- ---------- ---------- ---------- 2009 1 50000 2010 1 35000 2009 3 25000 2009 2 30000 15000 40000 2010 2 60000 SQL>