-3

我想用遞歸查詢(也可以是cte或任何東西),在那裏我試圖拉執行報告 - 在這裏我輸入一個員工的姓名,我想所有與層次員工從最高層的員工(從首席執行官開始)開始,然後走下坡路。T-SQL的遞歸查詢 - 員工層次

例如:

如果我輸入了員工姓名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'), 
+2

請仔細閱讀[這](http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a -public-forum /)提供一些關於改善問題的提示。提示:它應該包括一個問題。 – HABO

回答

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)。我們都MgrXCEO的:

Head  WhoIs 
--------- ----- 
Smith  CEO 
MacCormic CEO 
Wake  MgrX 
Malkovich MgrX 
Whatever MgrX 

(5 row(s) affected)