SQL CTE 递归:返回父记录
我当前正在运行 CTE 查询,以从员工表递归地构建员工层次结构,类似于大多数递归示例所演示的内容。我陷入困境的是,我正在尝试查询单个员工并检索他之上的层次结构。下面是我尝试使用的表的示例:
Employees
===========================================================================
EmployeeID MgrID Name
1 null Joe
2 1 John
3 2 Rob
4 2 Eric
下面是允许我从上到下显示层次结构的 SQL:
with employeeMaster as (
select p.EmployeeID, p.MgrID, p.Name
from Employees p
where p.MgrID is null
union all
select c.EmployeeID, c.MgrID, c.Name
from employeeMaster cte inner join Employees c on c.MgrID = cte.EmployeeID
)
select * from employeeMaster
我遇到的困难是我不知道如何查询最低级别员工,Rob 或 Eric,并从 Joe > 返回高于他的层次结构约翰>埃里克.看起来这应该很容易,但我一生都无法发现它。
I am currently running a CTE query to recursively build an employee hierarchy from an employees table similar to what most recursive examples demonstrate. Where I am stuck is that I am trying to query for a single employee and retrieve the hierarchy above him. Below is an example of the table I am trying to work with:
Employees
===========================================================================
EmployeeID MgrID Name
1 null Joe
2 1 John
3 2 Rob
4 2 Eric
The following is the SQL that allows me to display the hierarchy from the top down:
with employeeMaster as (
select p.EmployeeID, p.MgrID, p.Name
from Employees p
where p.MgrID is null
union all
select c.EmployeeID, c.MgrID, c.Name
from employeeMaster cte inner join Employees c on c.MgrID = cte.EmployeeID
)
select * from employeeMaster
Where I am stuck is that I can't figure out how to query for the lowest level employee, either Rob or Eric, and return the hierarchy above him from Joe > John > Eric. It seems as though this should be easy but I can't spot it for the life of me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否正在寻找一个查询来根据层次结构的深度返回可变数量的列?或者只是一个字段中的串联字符串?
这是对您的查询的一个小更改,这将使埃里克和层次结构中高于他的任何人都可以。
Are you looking for a query to return a variable number of columns, depending on the depth of hierarchy? Or just a concatenated string in one field?
Here's a minor change to your query that will get Eric and anyone above him in the hierarchy.