返回Employee表 - SQL查询

时间:2014-01-23 20:02:27

标签: sql sql-server sql-server-2008

请找我的

Emp_Table

Employee    Manager Employee Status
001            001  Active
002            001  Terminate
003            002  Active
004            002  Active
005            004  Terminate
006            005  Terminate
007            006  Active
008            006  Terminate
009            006  Active

我想重新安排上表来代表每个员工应该有ACTIVE Manager 即在上面的员工003表中 - > 002(经理被终止)因为我需要将此行重新排列为活动管理器
我需要看到002根据我的上表002报告给谁 - > 001经理和活动也因为我需要更新为003经理是001

请查找我的结果表 - Emp_Reworked_Table

Employee    Manager Employee Status
001            001  Active
002            001  Terminate
003            001  Active
004            001  Active
005            004  Terminate
006            004  Terminate
007            004  Active
008            004  Terminate
009            004  Active

我已经尝试过并找到解决方案,但我不知道为所有员工执行的递归查询。请帮助

1 个答案:

答案 0 :(得分:6)

我可能会过度杀死下面的示例,但其中的要点是您可能想要使用recursive CTE

IF NOT EXISTS ( SELECT  1
                FROM    sys.objects
                WHERE   name = 'Emp_Table'
                    AND type = 'U' )
BEGIN
    --DROP TABLE dbo.Emp_Table;
    CREATE TABLE dbo.Emp_Table
    (
        EmpTable_PK         TINYINT IDENTITY( 1, 1 ) NOT NULL,
                                PRIMARY KEY ( EmpTable_PK ),
        EmployeeCode        CHAR( 3 ),
        ManagerCode         CHAR( 3 ),
        EmployeeStatus      VARCHAR( 16 )
    );

    INSERT INTO dbo.Emp_Table ( EmployeeCode, ManagerCode, EmployeeStatus )
    SELECT  EmployeeCode, ManagerCode, EmployeeStatus
    FROM (      SELECT  EmployeeCode = NULL, ManagerCode = NULL, EmployeeStatus = NULL
    UNION ALL   SELECT  '001', '001', 'Active'
    UNION ALL   SELECT  '002', '001', 'Terminate'
    UNION ALL   SELECT  '003', '002', 'Active'
    UNION ALL   SELECT  '004', '002', 'Active'
    UNION ALL   SELECT  '005', '004', 'Terminate'
    UNION ALL   SELECT  '006', '005', 'Terminate'
    UNION ALL   SELECT  '007', '006', 'Active'
    UNION ALL   SELECT  '008', '006', 'Terminate'
    UNION ALL   SELECT  '009', '006', 'Active' ) l
    WHERE   l.EmployeeCode IS NOT NULL
END;
GO

;WITH cte_Hierarchy AS (
    SELECT  et.EmpTable_PK, et.EmployeeCode, 
            et.ManagerCode, et.EmployeeStatus, 
            ManagerStatus = mt.EmployeeStatus
    FROM    dbo.Emp_Table et
    INNER JOIN dbo.Emp_Table mt
        ON  et.ManagerCode = mt.EmployeeCode
    UNION ALL
    SELECT  h.EmpTable_PK, h.EmployeeCode,
            ManagerCode = et.ManagerCode, 
            h.EmployeeStatus,
            mt.EmployeeStatus
    FROM    cte_Hierarchy h
    INNER JOIN dbo.Emp_Table et
        ON  h.ManagerCode = et.EmployeeCode
    INNER JOIN dbo.Emp_Table mt
        ON  et.ManagerCode = mt.EmployeeCode
    WHERE   h.ManagerStatus = 'Terminate'
        AND et.EmployeeCode <> et.ManagerCode )
SELECT  EmployeeCode, ManagerCode, EmployeeStatus
FROM    cte_Hierarchy
WHERE   ManagerStatus = 'Active'
ORDER BY EmpTable_PK, EmployeeCode, ManagerCode;