根据层次结构树将员工关联到部门

时间:2017-05-23 15:11:00

标签: sql sql-server

我试图弄清楚如何构建一个查询来根据组织层次结构来整理部门关联。因此,John位于sales,并向Jane报告MikeJane应继承salesMike也应继承销售部门。

示例表

+-------+------------+------------+
| Name  | Department | Supervisor |
+-------+------------+------------+
| John  | Sales      | Jane       |
| Jane  | Supervisor | Mike       |
| Fred  | Supervisor | Mike       |
| Alex  | Retail     | Fred       |
| Mike  | Manager    | ---        |
| Chris | Sales      | Jane       |
| Dan   | Retail     | Fred       |
+-------+------------+------------+

树的样子

enter image description here

预期输出

+-------+------------+
| Name  | Department |
+-------+------------+
| John  | Sales      |
| Jane  | Supervisor |
| Jane  | Sales      |
| Fred  | Supervisor |
| Fred  | Retail     |
| Alex  | Retail     |
| Mike  | Manager    |
| Mike  | Sales      |
| Mike  | Retail     |
| Chris | Sales      |
| Dan   | Retail     |
+-------+------------+

在过去的两周里,我尝试过很多东西,但是还没有接近代表我想要的输出。我相信这超出了我的SQL知识,我没有(甚至部分)工作代码在这里显示。

我怎样才能做到这一点?

CREATE TABLE Employees
    (Name varchar(5), Department varchar(10), Supervisor varchar(4))
;

INSERT INTO Employees
    (Name, Department,Supervisor)
VALUES
    ('John', 'Sales', 'Jane'),
    ('Jane', 'Supervisor', 'Mike'),
    ('Fred', 'Supervisor', 'Mike'),
    ('Alex', 'Retail', 'Fred'),
    ('Mike', 'Manager', '---'),
    ('Chris', 'Sales', 'Jane'),
    ('Dan', 'Retail', 'Fred')
;

1 个答案:

答案 0 :(得分:2)

您可以使用递归使用 CTE执行此操作。

Link on MSDN 了解有关递归CTE的更多信息

查询

--CREATE TABLE Employees
--    (Name varchar(5), Department varchar(10), Supervisor varchar(4))
--;

--INSERT INTO Employees
--    (Name, Department, Supervisor)
--VALUES
--    ('John', 'Sales', 'Jane'),
--    ('Jane', 'Supervisor', 'Mike'),
--    ('Fred', 'Supervisor', 'Mike'),
--    ('Alex', 'Retail', 'Fred'),
--    ('Mike', 'Manager', '---'),
--    ('Chris', 'Sales', 'Jane'),
--    ('Dan', 'Retail', 'Fred')
--;

WITH user_cte AS (
SELECT Name, Department,Supervisor
FROM Employees
WHERE Department ='Retail' or Department='Sales'
UNION ALL
SELECT 
t.Name, ucte.Department,t.Supervisor
FROM Employees t
INNER JOIN user_cte ucte ON ucte.Supervisor = t.Name
)
SELECT DISTINCT Name,Department
FROM user_cte
UNION 
SELECT Name, Department 
FROM Employees
GO

<强>解释

递归CTE是SQL Server中常见的编程结构。需要注意的重要一点是,默认情况下它们最多可以嵌套100个级别。如果您需要更深入地使用MAXRECURSION查询提示

单独使用CTE并不能提供完整的输出,您需要使用UNION表达式从原始表中添加缺少的行。