纵向排列如何改成横向的?????????
纵向排列如何改成横向的?????????
oracle的sql语句如下:
select distinct
zla.authorized_person
from sdcd.zdeco_head_all h,sdcd.zdeco_line_all zla
where h.zdeco_head_id=zla.zdeco_head_id
and h.zdeco_head_number='2012049'
运行结果:
authorized_person
张三
李四
王五
但是我想要的是下面的效果:
authorized_person
张三,李四,王五
或者
authorized_person
张三 李四 王五
请问这条SQL语句应该怎么修改?????????
[解决办法]
select
MAX(decode(zla.authorized_person ,'张三',zla.authorized_person||',',NULL)) ||
MAX(decode(zla.authorized_person,'李四',zla.authorized_person||',',NULL))||
MAX(decode(zla.authorized_person,'王五',zla.authorized_person||',',NULL)) as authorized_person
from sdcd.zdeco_head_all h,sdcd.zdeco_line_all zla
where h.zdeco_head_id=zla.zdeco_head_id
and h.zdeco_head_number='2012049'
注意:Max Decode Group by必须联合使用。
[解决办法]
参照经典行列转换
[解决办法]
sys_connect_by_path
[解决办法]
--横列转换create table TTbl1 as select 2000 nyear,'王五' sname,'2w' sSalary from dualunion select 2000,'马三','3w' from dualunion select 2001,'王五','4w' from dualunion select 2001,'马三','6w' from dual; declare cursor c1 is select nyear,avg(case when instr(sSalary,'w')>0 then To_number(substr(sSalary,1,instr(sSalary,'w')-1)) else 0 end) as sSalary1 from ttbl1 group by nyear order by nyear asc; sSql varchar2(2000); sSql1 varchar2(2000); sSql2 varchar2(2000); icount number; c2 c1%rowtype; vTbl varchar2(20); function CheckTableExist(NewTableName varchar2) return integer asv_Count integer;begin select count(*) into v_Count from user_tables where upper(trim(table_name))=upper(trim(NewTableName)); if v_Count=0 then return 0; else return 1; end if; exception when others then return 0;end;begin sSql := 'create table TmpTbl1('; sSql1 := 'insert into TmpTbl1'; sSql2 := ' select '; icount := 0; open c1; loop fetch c1 into c2; exit when c1%notfound; icount := icount+1; if iCount = 1 then sSql := sSql||'y'||c2.nyear||' varchar2(20)'; sSql2 := sSql2||c2.sSalary1; else sSql := sSql||',y'||c2.nyear||' varchar2(20)'; sSql2 := sSql2||','||c2.sSalary1; end if; end loop; close c1; sSql := sSql||')'; sSql2 := sSql1||' '||sSql2||' from dual'; vTbl := 'TmpTbl1'; if CheckTableExist(vTbl) = 1 then execute immediate 'drop table '||vTbl; end if; execute immediate sSql; execute immediate sSql2; commit;end;select * from TmpTbl1;