以下是适用于您的数据的 UNPIVOT(适用于 Oracle 11+ 版本)示例:
DROP TABLE mytable;
CREATE TABLE mytable(
OBJECT_ID INTEGER NOT NULL PRIMARY KEY
,CD_1 INTEGER NOT NULL
,NM_1 VARCHAR(15) NOT NULL
,CD_2 INTEGER NOT NULL
,NM_2 VARCHAR(28) NOT NULL
,CD_3 INTEGER NOT NULL
,NM_3 VARCHAR(20) NOT NULL
,CD_4 INTEGER NOT NULL
,NM_4 VARCHAR(28) NOT NULL
,CD_5 INTEGER NOT NULL
,NM_5 VARCHAR(16) NOT NULL
,DT VARCHAR(14) NOT NULL
);
insert into mytable
SELECT 53027429 AS OBJECT_ID,53001326 AS CD_1,'CEO & President' AS NM_1,53000330 AS CD_2,'Merck Manufacturing Division' AS NM_2,53011048 AS CD_3,'EMEA Operations' AS NM_3,54001626 AS CD_4,'HSC PLANT DIRECTION' AS NM_4,53027385 AS CD_5,'HSC NOT STERILE' AS NM_5,'4/24/2013 8:22' AS DT from dual
UNION ALL
SELECT 54010819,53001326,'CEO & President',54002711,'Merck Consumer Care',54007326,'MCC Emerging Markets',54010308,'Consumer Care - Asia Pacific',54010819,'MCC Singapore','8/23/201211:26' from dual
UNION ALL
SELECT 53025491,53001326,'CEO & President',53000330,'Merck Manufacturing Division',53011048,'EMEA Operations',54003518,'Rathdrum - Plant Manager',53020040,'Engineering & FM','5/22/2012 6:24' from dual
UNION ALL
SELECT 53023206,53001326,'CEO & President',53000321,'Corporate Finance',53000333,'MMD Finance',54001411,'Operations',54004358,'MMD Finance EMEA','5/31/2012 6:51' from dual
UNION ALL
SELECT 53021255,53001326,'CEO & President',53008586,'Global Human Health',54001286,'EUCan1',53013126,'Mid-Europe 1',53019000,'MER-1 Balkans','3/14/2013 7:06' from dual;
commit;
select distinct cd, nm,
case when parent=cd then 0 else parent end as parent, lvl
from (
select * from mytable
unpivot (
(cd, nm, parent) for lvl in ((CD_1, NM_1, CD_1) as 1,(CD_2, NM_2, CD_1) as 2,(CD_3, NM_3, CD_2) as 3,(CD_4, NM_4, CD_3) as 4, (CD_5, NM_5, CD_4) as 5)
)
)
order by lvl;
输出:
CD NM PARENT LVL
---------- ---------------------------- ---------- ----------
53001326 CEO & President 0 1
53000321 Corporate Finance 53001326 2
53008586 Global Human Health 53001326 2
54002711 Merck Consumer Care 53001326 2
53000330 Merck Manufacturing Division 53001326 2
53011048 EMEA Operations 53000330 3
54001286 EUCan1 53008586 3
54007326 MCC Emerging Markets 54002711 3
53000333 MMD Finance 53000321 3
54010308 Consumer Care - Asia Pacific 54007326 4
54001626 HSC PLANT DIRECTION 53011048 4
53013126 Mid-Europe 1 54001286 4
54001411 Operations 53000333 4
54003518 Rathdrum - Plant Manager 53011048 4
53020040 Engineering & FM 54003518 5
53027385 HSC NOT STERILE 54001626 5
54010819 MCC Singapore 54010308 5
53019000 MER-1 Balkans 53013126 5
54004358 MMD Finance EMEA 54001411 5
19 rows selected.