我想运行一个递归CTE这样我就可以得到表2之间所有可能的关系,用表提供的信息1.SQL递归:获得父母和后代
表1:
Employee | ReportsTo
a NULL
b a
c b
d c
表2:
Employee | ReportsTo | depth
a NULL 0
b a 1
c a 2
d a 3
c b 1
d b 2
d c 1
到目前为止,我有:
with cte
(Employee
,ReportsTo
,depth)
as
(
select Employee
,ReportsTo
,0 as depth
from [Table 1]
where ReportsTo is null
UNION ALL
select a.Employee
,a.ReportsTo
,b.depth + 1
from cte b
join [Table 1] a
on a.ReportsTo = b.Employee
)
select *
from cte
order by depth
返回:
Employee | ReportsTo | Depth
a NULL 0
b a 1
c b 2
d c 3
举了几个例子来说明我的问题,注意,我缺少的“d”间接雇员“B”举报员工之间的关系。或员工“d”间接向员工“a”报告。
@Amit我不认为在链接中提供的答案正是我所期待的。我想要实现表2中的结果,而不是通过WHERE子句指定Employee或ReportsTo的值。任何其他建议? – Paramus
您正在使用哪个[DBMS](https://en.wikipedia.org/wiki/Database)? –