我是SQL的新手,正在研究一个列表以生成带有报告副总裁的员工列表。我面临的挑战是并非所有员工都直接向副总裁报告,有些人需要通过多个报告渠道才能到达副总裁。
我所做的是为每个报告渠道创建CTE并尝试加入,但这种方法仍然无法正常工作。例如,如果员工A向主管报告,然后主管向经理报告,然后主管向高级经理报告,然后高级经理向主管报告,而主管向其业务部门副总裁报告,那么我需要一个表格来列出员工A和负责该业务部门的副总裁的信息,格式如下 员工编号,名字,姓氏,用户名,职务,VPusername 以下是我提出的脚本。有人可以查看一下并让我知道我做错了吗?
任何帮助将不胜感激
With Employee
as
(
SELECT [EmployeeNumber]
,[SupervisorEmployeeNumber]
FROM [BASE_DB].[dbo].[HR_list_180604]
),
Tier1sup
as
(
SELECT sup1.[EmployeeNumber]
--,emp.[EmployeeNumber]
,sup1.[Username]
,sup1.[JobTitle]
,sup1.[SupervisorEmployeeNumber]
FROM [BASE_DB].[dbo].[HR_list_180604] sup1
left join Employee as emp on emp.[SupervisorEmployeeNumber] = sup1.[EmployeeNumber]
where sup1.[JobTitle] like '%VP,%'
),
Tier2sup
as
(
SELECT sup2.[EmployeeNumber]
--,emp.[EmployeeNumber]
,sup2.[Username]
,sup2.[JobTitle]
,sup2.[SupervisorEmployeeNumber]
FROM [BASE_DB].[dbo].[HR_list_180604] sup2
left join Tier1sup as tier1 on Tier1.[SupervisorEmployeeNumber] = sup2.[EmployeeNumber]
--left join Employee as emp on emp.[SupervisorEmployeeNumber] = Tier1sup.[SupervisorEmployeeNumber]
where sup2.[JobTitle] like '%VP,%'
),
Tier3sup
as
(
SELECT sup3.[EmployeeNumber]
--,emp.[EmployeeNumber]
,sup3.[Username]
,sup3.[JobTitle]
,sup3.[SupervisorEmployeeNumber]
FROM [BASE_DB].[dbo].[HR_list_180604] sup3
left join Tier2sup as tier2 on Tier2.[SupervisorEmployeeNumber] = sup3.[EmployeeNumber]
where sup3.[JobTitle] like '%VP,%'
)
select T1.[EmployeeNumber]
,T1.[FirstName]
,T1.[LastName]
,T1.[Username]
,T1.[JobTitle]
,case
when sup1.[JobTitle] like '%VP,%' then sup1.[Username]
when sup2.[JobTitle] like '%VP,%' then sup2.[Username]
when sup3.[JobTitle] like '%VP,%' then sup2.[Username]
end as SupUser
from [BASE_DB].[dbo].[HR_list_180604] T1
left join Employee as emp on T1.[EmployeeNumber] = emp.[EmployeeNumber]
left join Tier1sup as sup1 on sup1.[EmployeeNumber] = emp.[SupervisorEmployeeNumber]
left join Tier2sup as sup2 on sup2.[EmployeeNumber] = sup1.[SupervisorEmployeeNumber]
left join Tier3sup as sup3 on sup3.[EmployeeNumber] = sup2.[SupervisorEmployeeNumber]