There is a dept_employees hierarchy dept_employees
| ID | parent_id | obj_id | obj_type | +----+-----------+--------+----------+ | 10 | null | 1 | dept | | 11 | 10 | 2 | dept | | 12 | 11 | 1 | emp | | 13 | 11 | 2 | emp | | 14 | 13 | 3 | emp | | 15 | 12 | 4 | emp | The hierarchical table stores the list of departments and employees.obj_id refers to the employees and ogpo_dept
And there are tables of employees, departments and point-of-sale terminals:
dbo.employees dbo.ogpo_dept dbo.cash_extensions | ID | FIO | dept_id | | ID | Name | | ID | FIO | +----+------+---------| +----+--------+ +----+---------+ | 1 | Аня | 1 | | 1 | ГО | | 1 | Аня | | 2 | Ира | 1 | | 2 | Астана | | 2 | Макс | | 3 | Макс | 1 | | 3 | Юля | | 4 | Юля | 1 | I need to transfer the employee id and pull out from the hierarchical table look from the employee (who passed the ID) to the upstream and downstream employees who are in the dbo.cash_extensions table
My recursive query:
with cteTop as ( --первый cte выбирает вышестоящую сущность select de.id, de.parent_id, de.obj_id from [dbo].[dept_employees] de where de.id = 12 union all select de.id, de.parent_id, de.obj_id from [dbo].[dept_employees] de inner join cteTop c on c.parent_id = de.id ), cteBot as ( -- выбираем нижестоящих select de.id, de.parent_id, de.obj_id from [dbo].[dept_employees] de where de.id = 12 union all select de.id, de.parent_id, de.obj_id from [dbo].[dept_employees] de inner join cteBot c on c.id = de.parent_id ) select e.fio from cteTop left join ogpo_dept od on od.id = cteTop.obj_id left join employees e on e.dept_id = od.id inner join Cash.dbo.cash_extensions ce on ce.fio=e.fio union all select e.fio from cteBot left join ogpo_dept od on od.id = cteBot.obj_id left join employees e on e.dept_id = od.id inner join cash_extensions ce on ce.fio=e.fio Query result:
| FIO | +-----+ | Аня | | Юля | The result should be:
| FIO | +------+ | Аня | | Юля | | Макс | The question is how to pull out all the employees of the higher branch and downstream employees from the current employee?