我有一个像
这样的员工表emp_id bigint,
reports_to bigint,
emp_name varchar(20),
Constraint [PK_Emp] Primary key (emp_id),
Constraint [FK_Emp] Foreign key (reports_to) references [MSS].[dbo].[Emp]([emp_id])
emp_id reports_to emp_name
------ ------ --------------
1 null Sumanta
2 1 Arpita
3 null Pradip
4 1 Sujon
5 2 Arpan
6 5 Jayanti
我想让直接或间接向Sumanta或emp_id(1)报告的所有员工,以及层次结构级别,如下所示:
emp_id hierarchy_level emp_name
------ --------------- ----------
2 1 Arpita
4 1 Sujon
5 2 Arpan
6 3 Jayanti
我是SQL的新手,无法找到使用的内容或如何获得这些结果。值得存储过程与表值变量,或只是一个Tsql选择查询就足够了。我们非常欢迎任何帮助。
我所做的只是 -
Select Ep.emp_id,ep.emp_eame
From Emp as E
Inner Join Emp as Ep on Ep.reports_to=E.Emp_id
Where E.reports_to=1 or E.emp_id=1;
但这准确到2级,我甚至无法生成hierarchy_level否。 任何建议,想法............将是最有帮助的.........
答案 0 :(得分:12)
您可以使用递归CTE:
; with CTE as
(
select emp_id
, reports_to
, emp_name
, 1 as level
from Emp
where emp_name = 'Sumanta'
union all
select child.emp_id
, child.reports_to
, child.emp_name
, level + 1
from Emp child
join CTE parent
on child.reports_to = parent.emp_id
)
select *
from CTE
答案 1 :(得分:0)
使用Common_Table_Expression我们可以这样写
WITH Employee_CTE(employeeid,hierarchy_level,name) AS
(
SELECT employeeid,1 as level,name from employee where employeeid=1
UNION ALL
SELECT e.employeeid,level +1, e.name
from employee e
INNER JOIN Employee_CTE c ON e.employeeid = c.managerid
)
SELECT * FROM Employee_CTE order by employeeid