1. 程式人生 > >oracle 動態交叉查詢 行列互換 oracle動態交叉表

oracle 動態交叉查詢 行列互換 oracle動態交叉表

 column_col in varchar2,--要從行轉成列的欄位
 value_col in varchar2,--需要聚合的值欄位
Aggregate_func in varchar2 default 'max',--選用的聚合函式,可選,預設為max
 condition in varchar2 default '1=1',--條件語句,可選
 colorder in varchar2 default null,--行轉列後列的排序,可選
 roworder in varchar2 default null,--行轉列後記錄的排序,可選
when_value_null in varchar2 default null,--若value_col欄位的值聚合後為空,則轉換成該值,可選
viewname in varchar2 default 'v_tmp'--建立的檢視名稱,可選,預設為v_tmp
)
Authid Current_User
as
c1 sys_refcursor;
v1 varchar2(1000);
sqlstr varchar2(10000);
countTemp number(10);
begin
EXECUTE IMMEDIATE 'select count(distinct '||column_col||') from '||tabname into countTemp;
sqlstr :='create or replace view '||viewname||' as select '||group_col||','
||Aggregate_func||'('||value_col||') as "summation",round('|| Aggregate_func||'('||value_col||')/'||countTemp||',2) as "average"';
open c1 for 'select distinct '||column_col||' from '||tabname||' where '||condition|| 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||' where '||condition||' group by '||group_col||case when roworder is not null then ' order by '||roworder end;
execute immediate sqlstr;
end dw_dis_proc;