如何调用递归查询?

时间:2018-09-20 09:03:38

标签: sql sql-server

我有一个类似下面的表格

  emp_id    emp_name    manager_id
    A1          A           C1
    B1          B           C1
    C1          C           D1
    D1          D           F1
    E1          E           F1
    F1          F           G1
    G1          G           
  • 如果有人问谁向C1报告,它应该返回B1,A1
  • 如果有人问谁向D1汇报,则应返回C1,B1,A1
  • 如果有人问谁向F1汇报,则应返回E1,D1,C1,A1,B1
  • 如果有人问谁向G1汇报,则应返回F1,E1,D1,C1,A1,B1

我是写sql查询的新手。能帮我写一个满足上述要求的查询吗?谢谢。

关于, 潘卡(Pankaj)

3 个答案:

答案 0 :(得分:0)

此查询此处显示员工的直接报告经理是谁。也许您可以在问题中添加一些内容,使其更易于理解。

WITH cte
AS (
    SELECT emp_id
        ,emp_name
        ,manager_id
    FROM emp
    WHERE emp_id = 'G1'
    UNION ALL
    SELECT E.emp_id
        ,E.emp_name
        ,E.manager_id
    FROM emp E
    INNER JOIN cte c ON E.emp_id = c.emp_id
    )
SELECT emp_id
    ,emp_name
    ,cast(coalesce(manager_id, 'Boss') AS VARCHAR(max) FROM cte)

答案 1 :(得分:0)

递归cte

;WITH CTE_Recursive(emp_id,emp_name,manager_id)
AS
(
SELECT 'A1','A','C1' UNION ALL
SELECT 'B1','B','C1' UNION ALL
SELECT 'C1','C','D1' UNION ALL
SELECT 'D1','D','F1' UNION ALL
SELECT 'E1','E','F1' UNION ALL
SELECT 'F1','F','G1' UNION ALL 
SELECT 'G1','G',NULL
)
,CTE_Result
AS
(
SELECT  Emp_ID,
        Emp_name,
        CAST(Emp_name  AS VARCHAR(100))AS Boss
FROM CTE_Recursive
WHERE manager_id IS NULL
UNION ALL
SELECT  e.Emp_ID,
        e.Emp_name,
        CAST(Boss+ '\'+e.Emp_name  AS VARCHAR(100)) AS Boss

FROM CTE_Result c
INNER JOIN CTE_Recursive e
ON e.manager_id=c.Emp_ID
)
SELECT * FROM CTE_Result

答案 2 :(得分:0)

;WITH temp(empid,empname,empManagerID)  
AS  
(  
SELECT 'A1','A','C1' UNION ALL  
SELECT 'B1','B','C1' UNION ALL  
SELECT 'C1','C','D1' UNION ALL  
SELECT 'D1','D','F1' UNION ALL  
SELECT 'E1','E','F1' UNION ALL  
SELECT 'F1','F','G1' UNION ALL   
SELECT 'G1','G',NULL  
)  
, CTE_Recrusive  
AS  
(  
SELECT empid,empname,empManagerID  
FROm TEMP  
WHERE empManagerID='G1'  
UNION ALL  
SELECT  t.empid,t.empname,t.empManagerID  
FROm CTE_Recrusive c  
INNER JOIN TEMP t on c.empid = t.empManagerID  
)  
select * from  CTE_Recrusive