I have a simple query:
SELECT DISTINCT
dep.DEP_ID,
dep.DEP_NAME,
dep.PARENT_DEP_ID,
emp.SITE_LOCATION
from DEPARTMENT dep
INNER JOIN EMPLOYEE emp ON dep.DEP_ID = emp.DEP_ID
ORDER BY dep.DEP_ID;
This returns information about departments
with some rows having the same DEP_ID
, DEP_NAME
and PARENT_DEP_NAME
. This is the expected result because some employees belong to the same department but have a different SITE_LOCATION
What I'd like is to add another column MASTER_PARENT_ID
with the DEP_ID
of the MASTER parent.
What I call master parent is the one which is referenced as PARENT_DEP_ID
but actually doesn't exist (missing value in the DEP_ID
column).
So all these rows should actually have a MASTER_PARENT_ID
value equals to DEP_2000
. This is just a sample data but in reality many rows would have a different MASTER_PARENT_ID
. Not all of them would have the same value.
To do that, for each row, I need to execute a recursive query to go all the way trough the tree until I find a PARENT_DEP_ID
value that doesn't have any matching DEP_ID
.
I'm trying to read and understand the Oracle documentation and examples but I can't find what's working in my case. Should I use something like CONNECT BY PRIOR
to perform such recursive function?
SQL in general isn't my cup of tea and even less Oracle. I can't find how to solve this problem.
Thank you