Employee Manager Report - Sql Server

后端 未结 4 1281
借酒劲吻你
借酒劲吻你 2021-01-28 21:14

I have the below table

empid   empname     managerID
1          A          NULL
2          B           1
3          C           1
4          D           2
         


        
4条回答
  •  心在旅途
    2021-01-28 21:47

    Declare @t table(empid int, empname varchar(20), managerID int)
    
    insert into @t 
    select 1,'A',null union all
    select 2,'B',1 union all
    select 3,'C',1 union all 
    select 4,'D',2
    
    ;with CTE AS
    (
        Select empid,empname,managerID,
        Cast(empname As Varchar(max)) As ReportingManager
        from @T
        where managerID is null
    
        UNION ALL
    
        Select T.empid,T.empname,T.managerID,
        Cast(CTE.empname+'->'+t.empname As Varchar(max)) As ReportingManager
        from @T As T
        INNER JOIN CTE ON T.managerID=CTE.empid 
    )
    SELECT *
    FROM CTE
    
    

提交回复
热议问题