SQL get multiply子元素

时间:2017-09-21 02:31:46

标签: sql sql-server

我有一张表代表n级亲子关系。

   ParentID  ChildID
1   A        B
2   B        C
3   B        D
3   C        E
......

如果我有父ID,如何在SQL语句中包含所有A,B,C,D,E(假设每个元素都可以有子/ s,那么可能需要一些递归)。

1 个答案:

答案 0 :(得分:0)

听起来你想要的是一个递归的公用表表达式(CTE)。提取层次结构很好。

此链接应该有所帮助:MSDN Recursive Queries Using Common Table Expressions 我已经复制了下面的主要示例。

USE AdventureWorks2008R2;
GO
WITH DirectReports (ManagerID, EmployeeID, Title, DeptID, Level)
AS
(
-- Anchor member definition
    SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID, 
        0 AS Level
    FROM dbo.MyEmployees AS e
    INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh
        ON e.EmployeeID = edh.BusinessEntityID AND edh.EndDate IS NULL
    WHERE ManagerID IS NULL
    UNION ALL
-- Recursive member definition
    SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID,
        Level + 1
    FROM dbo.MyEmployees AS e
    INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh
        ON e.EmployeeID = edh.BusinessEntityID AND edh.EndDate IS NULL
    INNER JOIN DirectReports AS d
        ON e.ManagerID = d.EmployeeID
)
-- Statement that executes the CTE
SELECT ManagerID, EmployeeID, Title, DeptID, Level
FROM DirectReports
INNER JOIN HumanResources.Department AS dp
    ON DirectReports.DeptID = dp.DepartmentID
WHERE dp.GroupName = N'Sales and Marketing' OR Level = 0;
GO