1

这是我的问题。我有一个员工数据表,其中包含员工的用户名及其经理的用户名,如下所示

 ______________________________________________
| employee_username | employee_manager_username|
------------------------------------------------
  tom01             |         mark2
  mark2             |         bill3

我的问题是,如何进行选择,对于任何行,包含employee_manager_username 作为employee_username 的行位于之前?我想使用我的示例,我该如何做到这一点,以便在选择中,[mark3,bill3] 行位于 [tom01,mark2] 行之前。

长话短说,我有一个第 3 方导入流程,它会警告找不到经理。能够在他们的下属之前导入经理将使日志不那么啰嗦。

非常感谢您对此的任何帮助。

4

1 回答 1

3

我假设您有顶级经理有employee_manager_username = null。在这种情况下,您可以递归公用表表达式,然后按级别排序:

;with CTE as (
    select t.employee_username, t.employee_manager_username, 1 as level
    from table1 as t
    where
          t.employee_manager_username is null or 
          t.employee_manager_username = t.employee_username

    union all

    select t.employee_username, t.employee_manager_username, c.level + 1 as level
    from table1 as t
        inner join CTE as c on c.employee_username = t.employee_manager_username
    where
        not (
            t.employee_manager_username is null or 
            t.employee_manager_username = t.employee_username
        )
)
select *
from CTE
order by level asc

用于测试查询的SQL FIDDLE 示例

于 2013-08-01T21:03:56.277 回答