典型行转列,请高手赐教,快速散分结贴!
当前数据:
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;
select t.aid,
t.bid,
t.bname,
max(decode(t.akey, 1, t.akey, 0)) Akey,
max(decode(t.akey, 2, t.akey, 0)) Akey,
max(decode(t.akey, 3, t.akey, 0)) Akey,
max(decode(t.avalue, 'P1', t.avalue, 0)) AValue,
max(decode(t.avalue, 'P2', t.avalue, 0)) AValue,
max(decode(t.avalue, 'P3', t.avalue, 0)) AValue
from tx t
group by t.aid, t.bid, t.bname;