I have a table which has rows in a parent child relationship. The maximum parent-child relationship depth is 3.
One parent would have only one child.
Table definition -
CREATE TABLE USERS {
empid NUMBER,
name VARCHAR2,
department VARCHAR2(20),
oldempid NUMBER,
}
Data -
EMPID NAME DEPARTMENT OLDEMPID
1 FOO IT 2
2 null HR 4
3 BAR ADMIN null
4 null DESIGN null
Desired output -
EMPID NAME DEPARTMENT_1 DEPARTMENT_2 DEPARTMENT_3
1 FOO IT HR DESIGN
3 BAR ADMIN null null
Full Desired output -
EMPID NAME DEPARTMENT_1 DEPARTMENT_2 DEPARTMENT_3 OLDEMPID_1 OLDEMPID_2
1 FOO IT HR DESIGN 2 4
3 BAR ADMIN null null null null
I have tried using CONNECT BY PRIOR
SELECT CONNECT_BY_ROOT EMPID,
NAME,
RTRIM(LTRIM(SYS_CONNECT_BY_PATH(DEPARTMENT, '-'), '-'), '-') AS DEPARTMENT,
RTRIM(LTRIM(SYS_CONNECT_BY_PATH(OLDEMPID, '-'), '-'), '-') AS OLDEMPID
FROM USERS
WHERE CONNECT_BY_ISLEAF = 1
CONNECT BY PRIOR OLDEMPID = EMPID;
The output I get is -
EMPID NAME DEPARTMENT OLDEMPID
1 null IT-HR-DESIGN 1-2-4
3 BAR ADMIN null