我有一个问题,我无法找到一个好的答案。它看起来像递归是关键,但有一些计数和ifs,我不知道如何实现。这完全在SQL Server 2012中。
有两个表,M0是一个ID。
表1:EMP_MGR
EMP_Name | EMP_ID | EMP_Email | MGR_Name | MGR_ID | MGR_Email
表2:CO_SPOC
CO_Name | CO_M0 | CO_Email | SPOC | SPOC_M0 | SPOC_Email
问题在于我们需要一个循环,将员工和经理视为一个步骤。那是第1步。如果经理是CO(并非所有经理都是CO)那么这就是最高层和最后层。我们想要计算一名员工来自CO的经理人的步数。如果该经理不是CO,它会循环通过他们并查看他们的经理是否是CO。梯子越往下,步数越高
EMP_M0 MGR_M0 CO_M0 Steps
1 2 null 2
2 3 null 1
3 4 4 0
我使用此连接来构建EMP_M0,MGR_M0,CO_M0表。
select EMP_MGR.EMP_M0, EMP_MGR.MGR_M0, CO_SPOC.CO_M0
from EMP_MGR left join CO_SPOC
on EMP_MGR.MGR_M0 = CO_SPOC.CO_M0
order by EMP_MGR.EMP_M0
我如何通过这个来计算“世代”?#?然后重复,直到MGR_M0 = CO_M0。然后在整个集合中重复这一点,从具有最高步数和MGR_M0 = CO_M0 = 0的最低雇员分配降序值。
感谢您的任何想法或帮助!
编辑::如果这对样本数据不起作用,请告诉我。
declare @EMP_MGR table(EMP_Name varchar(64), EMP_M0 varchar(64), Emp_Email varchar(64), MGR_Name varchar(64), MGR_M0 varchar(64), MGR_Email varchar(64))
insert into @EMP_MGR
values
('Jake','M01111','Jake@work.org','John','M01112','John@work.org'),
('John','M01112','John@work.org','Johny','M01113','Johny@work.org'),
('Johny','M01114','Johny@work.org','Jimmy','M01115','Jimmy@work.org'),
('Jimmy','M01115','Jimmy@work.org','Steve','M00111','Steve@work.org'),
('Steve','M00111','Steve@work.org',null,null, null),
('Joslin','M01216','Joslin@work.org','Jasmine','M01217','Jasmine@work.org'),
('Jasmine','M01217','Jasmine@work.org','Jane','M01319','Jane@work.org'),
('Jane','M01319','Jane@work.org','Steve','M00111','Steve@work.org'),
('Jana','M01419','Jana@work.org','Josh','M01420','Josh@work.org'),
('Josh','M01420','Josh@work.org','Steve','M00111','Steve@work.org'),
('Jessica','M01421','Jessica@work.org','Jerry','M01422','Jerry@work.org'),
('Jerry','M01422','Jerry@work.org','Jordon','M01423','Jordon@work.org'),
('Jordon','M01423','Jordon@work.org','Jay','M01424','Jay@work.org'),
('Jay','M01424','Jay@work.org','Steve','M00111','Steve@work.org')
declare @CO_SPOC table (CO_Name varchar(64), CO_M0 varchar(64), CO_Email varchar(64), SPOC varchar(64), SPOC_M0 varchar(64), SPOC_Email varchar(64))
insert into @CO_SPOC
values
('Jimmy','M01115','Jimmy@work.org','Frank','M01911','Frank@work.org'),
('Jane','M01319','Jane@work.org','Francine','M01984','Francine@work.org'),
('Josh','M01420','Josh@work.org','Frank','M01911','Frank@work.org'),
('Jay','M01424','Jay@work.org','Fred','M01943','Fred@work.org')