如何以报告格式将员工与其经理联系起来

时间:2016-02-23 18:54:16

标签: sql-server

有人可以帮我解决以下问题吗?

的问题:

I need a SQL Server Query to generate a Report listing the Employees in their order of Job Profile Hierarchy

-

The CTE Query generates a wrong output in the first record with Manager Name and Job Profile where MgrID is NULL

样本数据是:

查询:

Select * From MyEmp;

结果:

EmpNo   EmpName JobProfile  DeptNo  MgrID   LevelID
7839    KING    PRESIDENT   10      NULL    01
7698    BLAKE   MANAGER     30      7839    02
7782    CLARK   MANAGER     10      7839    02
7566    JONES   MANAGER     20      7839    02
7654    MARTIN  SALESMAN    30      7698    03
7499    ALLEN   SALESMAN    30      7698    03
7844    TURNER  SALESMAN    30      7698    03
7900    JAMES   CLERK       30      7698    03
7521    WARD    SALESMAN    30      7698    03
7902    FORD    ANALYST     20      7566    03
7369    SMITH   CLERK       20      7902    04
7788    SCOTT   ANALYST     20      7566    03
7876    ADAMS   CLERK       20      7788    04
7934    MILLER  CLERK       10      7782    03

CTE查询是:

CTE查询:

WITH Subordinates AS
(
  (SELECT   e.EmpNo, e.EmpName, e.JobProfile, e.LevelID, e.MgrID,
            m.EmpName MgrName, m.JobProfile MgrProfile
   FROM MyEmp AS e
   INNER JOIN
        MyEmp AS m ON
            e.MgrID is NULL
            AND m.MgrID is NULL)
    UNION ALL
 (SELECT    e.EmpNo, e.EmpName, e.JobProfile, e.LevelID, e.MgrID,
            sub.EmpName MgrName, sub.JobProfile MgrProfile
   FROM MyEmp AS e 
   INNER JOIN 
        Subordinates AS sub ON 
            e.MgrID = sub.EmpNo
    )
)
SELECT * FROM Subordinates AS s;

结果:

EmpNo   EmpName JobProfile  LevelID MgrID   MgrName MgrProfile
7839    KING    PRESIDENT   01      NULL    KING    PRESIDENT
7698    BLAKE   MANAGER     02      7839    KING    PRESIDENT
7782    CLARK   MANAGER     02      7839    KING    PRESIDENT
7566    JONES   MANAGER     02      7839    KING    PRESIDENT
7902    FORD    ANALYST     03      7566    JONES   MANAGER
7788    SCOTT   ANALYST     03      7566    JONES   MANAGER
7876    ADAMS   CLERK       04      7788    SCOTT   ANALYST
7369    SMITH   CLERK       04      7902    FORD    ANALYST
7934    MILLER  CLERK       03      7782    CLARK   MANAGER
7654    MARTIN  SALESMAN    03      7698    BLAKE   MANAGER
7499    ALLEN   SALESMAN    03      7698    BLAKE   MANAGER
7844    TURNER  SALESMAN    03      7698    BLAKE   MANAGER
7900    JAMES   CLERK       03      7698    BLAKE   MANAGER
7521    WARD    SALESMAN    03      7698    BLAKE   MANAGER

带有CONNECT BY ... PRIOR TO的Oracle Query能够解决此问题,但我需要一个可以在SQL Server上有效的查询

Oracle Query

Select e.MgrID,
        --m.EmpName MgrName, m.JobProfile MgrProfile, 
        e.EmpNo, e.EmpName, e.JobProfile
   FROM MyEmp AS e 
  -- LEFT OUTER JOIN
  --        MyEmp AS m ON
  --        e.MgrID is NULL
        --AND m.MgrID is NULL
    START WITH e.MgrID is NULL
    CONNECT BY PRIOR EmpNo = MgrID
    ;

0 个答案:

没有答案