我有下表
TblMatrix
ID ApproverId
--------------------
1 4
2 7
7 8
4 5
5 6
我想编写一个自连接查询,以返回任何ApproverId
的输出如果我通过ApproverId As 6
输出应为
ID
---
5
4
1
如果我通过ApproverId As 8
输出应为
ID
---
7
2
答案 0 :(得分:3)
使用递归查询
with rcte as
(
select id from tblMatrix where approverId = 8
union all
select tblMatrix.id
from tblMatrix
join rcte on tblMatrix.approverid = rcte.id
)
select * from rcte