我想使用递归查询(它可以是cte
或任何东西)我试图提取执行报告 - 我输入一个员工姓名,我希望所有与该员工相关的层次结构从顶级的emloyee(从首席执行官开始)然后下降。
例如:
如果我输入员工姓名Celia
,报告应如下所示:
CEO
Employees reporting to CEO , let's say MgrX
Employees reporting to MgrX- let's say MgrY
Employees reporting to MgrY - let's say MgrZ
所有向MgrZ
报告的员工,包括Celia
(输入参数)。
我正在尝试使用的查询:
with cte1 as
(
select
pa.PERSNBR
,pa.AUTHCD
,pu.VALUE
,hr.File#
,hr.[Payroll Name]
,hr.[Reports To File#]
,hr.[Reports To Name]
,hr.[EMC #]
,hr.[EMC Name]
from
[DNA_Staging].[dbo].[PERSAUTH] pa
join [DNA_Staging].[dbo].[PERSEMPL] pe
on pa.PERSNBR = pe.PERSNBR
join [DNA_Staging].[dbo].[PERSUSERFIELD] pu
on pe.PERSNBR = pu.PERSNBR
and pu.USERFIELDCD = 'EFNR'
and GETDATE() < isnull(pe.inactivedate,getdate()+1)
join [HR_Staging].[dbo].[HR_EmployeeHierarchyStaging] hr
on pu.VALUE = substring(hr.File#,2,6)
or pu.VALUE = substring(hr.File#,3,6)
),
-- find all the data for input payroll name in the parameter
cte2 as (select *
FROM cte1 where [Payroll Name] = 'Acain, Celia T'),
答案 0 :(得分:0)
您问题的基本示例(您尚未提供任何数据样本或输出示例,因此......):
DECLARE @name nvarchar(20) = 'Darkwater'
;WITH emplevels AS (
SELECT *
FROM (VALUES
(1, 'CEO'),
(2, 'MgrX'),
(3, 'MgrY'),
(4, 'MgrZ')
) as t(eid, who)
),
people AS ( --people and there levels
SELECT *
FROM (VALUES
(1, 'Smith', 1),
(2, 'Wake', 2),
(3, 'Cartman', 3),
(4, 'Sanders', 4),
(5, 'MacCormic', 1),
(6, 'Malkovich', 2),
(7, 'Whatever', 2),
(8, 'Darkwater', 3),
(9, 'Leto', 4)
) as t(pid, name, eid)
),
dep AS ( --dependences of levels
SELECT *
FROM (VALUES
(1,1), --CEO - CEO
(1,2), --CEO - MgrX
(2,3), --MgrX - MgrY
(3,4) --MgrY - MgrZ
)as t(eid1,eid2)
),
hier as ( -- get the hierarchy
SELECT d.eid1,
d.eid2
FROM dep d
LEFT JOIN people p ON d.eid2 = p.eid
where name = @name
UNION ALL
SELECT d.eid1,
d.eid2
FROM dep d
INNER JOIN hier h ON d.eid2 = h.eid1
WHERE d.eid2 != d.eid1
)
--here comes heads and who there are
SELECT p.name AS Head,
e.who AS WhoIs
from hier h
LEFT JOIN people p ON p.eid = h.eid1
LEFT JOIN emplevels e ON e.eid = p.eid
ORDER BY e.eid
Darkwater
的结果(他是MgrY
)。我们拥有MgrX
和CEO
的所有内容:
Head WhoIs
--------- -----
Smith CEO
MacCormic CEO
Wake MgrX
Malkovich MgrX
Whatever MgrX
(5 row(s) affected)