问题
I have two tables Employee and Department this image shows the manager of every employee. I want to write a SQL query that gives me a list of all the supervisor (Manager, Manager of Manager..).
I just want a single column that displays a list of supervisor when given a particular employee.
E.g. If I give employee id = 202 then I should receive 200,130
|supervisor |
+-----------+
| 200 |
| 130 |
I have this query
WITH emp_dept as(
SELECT employee_id,manager_id
FROM employee,department
WHERE employee.dept_id= department.dept_id
)
WITH recursive p as (
select e1.employee_id, e1.manager_id
from emp_dept e1
where employee_id = 202
union all
select e2.employee_id , e2.manager_id
from p
join emp_dept e2 ON e2.employee_id = p.manager_id
)
select manager_id
from p
`
I am not able to use it. I am using pgadmin4.
If anyone could help me with this query I would greatly appreciate it
回答1:
I think you can use "hierarchical queries" for Oracle and try this:
select manager_id supervisor
from employee
start with employee_id = 202
connect by nocycle employee_id = prior manager_id;
回答2:
This is the solution to my question
with recursive p as (
WITH emp_dept as(
SELECT employee_id,manager_id
FROM employee,department
WHERE employee.dept_id= department.dept_id
)
select e1.employee_id, e1.manager_id
from emp_dept e1
where e1.employee_id = 202
union
select e2.employee_id , e2.manager_id
from p
join emp_dept e2 ON e2.employee_id = p.manager_id
)
select manager_id
from p
来源:https://stackoverflow.com/questions/49962130/sql-query-to-get-the-list-of-supervisor-hierarchy-employee-supervisor-s