oracle 动态交叉查询 行列互换 oracle动态交叉表

来源:互联网 发布:气象数据共享网 编辑:程序博客网 时间:2024/05/22 17:35

oracle 动态交叉查询 行列互换 oracle动态交叉表

 

使用视图 动态创建视图

SQL code
CREATE OR REPLACE procedure DWDEV.dw_dis_proc(tabname in varchar2,--需要进行行转列操作的表名
group_col in varchar2,--查询结果要按某列或某些列分组的字段名
 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;
select * from v_tmp

原创粉丝点击