【发布时间】:2023-11-20 22:01:01
【问题描述】:
我需要获取直接或间接依赖于某个人的所有员工的姓名。使用本例中的查询(来自https://rextester.com/WGVRGJ67798),
create table employee(
id int not null,
employee varchar(10) not null,
boss int null
)
insert into employee values
(1,'Anna',null),
(2,'Bob',1),
(3,'Louis',1),
(4,'Sara',2),
(5,'Sophie',2),
(6,'John',4);
with boss as (
select id, employee, boss, cast(null as varchar(10)) as name
from employee
where boss is null
union all
select e.id, e.employee, b.id, b.employee
from employee e
join boss b on b.id = e.boss
)
select * from boss
我可以得到这个结果:
但是,我需要看到这个:
这就像显示一个人与他或她“下方”的所有员工之间所有可能的关系。
【问题讨论】:
-
如果你用谷歌搜索
T-SQL hierarchical query,你会发现你需要一个递归 CTE -
@Larnu 好的,我的问题是如何修改递归 CTE 查询以获得第二张图像的绿色部分。通过 cte 查询,我得到了第一个查询的结果。这是我的疑问。
-
我已将您链接中的代码添加到您上面发布的问题中。请注意,重要的是问题要独立完成,而不依赖于其他网站(除非某些内容太大而无法包含在此处)。这是因为如果外部站点将来消失,那么您的问题对于以后可能得到答案的读者来说将不再有意义。因此,可以参考其他网站,但将它们用作补充/有用的来源,而不是必要的信息。
-
@RBarryYoung 非常感谢您的建议。下次我会记住的。
标签: sql sql-server hierarchical-data recursive-query