Oracle 11的PIVOT问题:当我执行以下操作时,我得到了数据存在的所有字段F2-F4中的数据的规范化结果。 F1是关键所以总是有数据:
select t1.F1, t2.F2, t2.F3, t2.F4
from schema.t1,
schema.t2
where
t1.F1 = t2.F1 (+)
现在我使用Oracle的PIVOT功能连接所有字段F2-F4,以便所有F2字段中有一个F2等字段,最多可连续5行,所有连接,如下所示:
select * from (
select F1,
TRIM("1_F2") || TRIM("2_F2") || TRIM("3_F2") || TRIM("4_F2") || TRIM("5_F2") as "F2",
TRIM("1_F3") || TRIM("2_F3") || TRIM("3_F3") || TRIM("4_F3") || TRIM("5_F3") as "F3",
TRIM("1_F4") || TRIM("2_F4") || TRIM("3_F4") || TRIM("4_F4") || TRIM("5_F4") as "F4"
from (
select ROWNUM as RN, T.* from (
select t1.F1, t2.F2, t2.F3, t2.F4
from schema.t1,
schema.t2
where
t1.F1 = t2.F1 (+)
) T
)
PIVOT (
MAX(F2) as "F2",
MAX(F3) as "F3",
MAX(F4) as "F4"
FOR RN in (1,2,3,4,5)
)
)
这是返回数据,例如,并非所有在F2行中找到的数据都会返回连接到所有记录的单个F2行。对于它确实有效的记录,实际上,我得到了归一化结果中的所有数据。但是,当它不起作用时,不返回在规范化结果中找到的数据。
有什么想法吗?我错过了什么?
提前致谢。
答案 0 :(得分:1)
好的,我使用了错误的功能。 Oracle LISTAGG功能完成了我需要做的事情。例如:
select F1,
LISTAGG (F2, ' ') within group (order by F1) as "F2",
LISTAGG (F3, ' ') within group (order by F1) as "F3",
LISTAGG (F4, ' ') within group (order by F1) as "F4"
from (
select t1.F1, t2.F2, t2.F3, t2.F4
from schema.t1,
schema.t2
where
t1.F1 = t2.F1 (+)
) group by F1
受欢迎的需求,一个例子:
create table myschema.t1 (
F1 varchar2(10)
)
create table myschema.t2 (
F1 varchar2(10),
F2 varchar2(10),
F3 varchar2(10),
F4 varchar2(10)
)
insert into myschema.t1 (F1) values ('1');
insert into myschema.t1 (F1) values ('1');
insert into myschema.t1 (F1) values ('1');
insert into myschema.t2 (F1,F2,F3,F4) values ('1','Hello1','World1','1');
insert into myschema.t2 (F1,F2,F3,F4) values ('1','Hello2','World2','2');
insert into myschema.t2 (F1,F2,F3,F4) values ('1','Hello3','World3','3');
commit;
select F1,
LISTAGG (F2, ' ') within group (order by F1) as "F2",
LISTAGG (F3, ' ') within group (order by F1) as "F3",
LISTAGG (F4, ' ') within group (order by F1) as "F4"
from (
select t1.F1, t2.F2, t2.F3, t2.F4
from myschema.t1,
myschema.t2
where
t1.F1 = t2.F1 (+)
) group by F1
你明白了:
F1 F2 F3 F4 -- -------------------------------------------------------------- -------------------------------------------------------------- ----------------- 1 Hello1 Hello1 Hello1 Hello2 Hello2 Hello2 Hello3 Hello3 Hello3 World1 World1 World1 World2 World2 World2 World3 World3 World3 1 1 1 2 2 2 3 3 3嗯,裁员多了?试试这个:
select F1,
LISTAGG (F2, ' ') within group (order by F1) as "F2",
LISTAGG (F3, ' ') within group (order by F1) as "F3",
LISTAGG (F4, ' ') within group (order by F1) as "F4"
from (
select distinct t1.F1, t2.F2, t2.F3, t2.F4
from myschema.t1,
myschema.t2
where
t1.F1 = t2.F1 (+)
) group by F1
你现在得到:
F1 F2 F3 F4 -- -------------------- -------------------- ---------- 1 Hello1 Hello2 Hello3 World1 World2 World3 1 2 3