如何从父子层次结构表创建查询

时间:2017-08-13 14:17:06

标签: sql sql-server parent-child

如何编写查询以将具有父/子层次结构的表转换为具有不同列中的层次结构级别的表?

我在SQL Server中有一个表(来自SAP而我没有做出任何更改),它为我提供了包含我的利润中心的组的结构。表的结构是经典的父子层次结构,如下所示。

Parent  |  Child  
--------+--------
S-1     |  S-11  
S-1     |  S-12  
S-1     |  S-13  
S-1     |  S-14  
S-1     |  S-15  
S-11    |  S-111  
S-11    |  S-112  
..      |  ..  
S-152   |  S-1521  
S-152   |  S-1522  
S-1522  |  S-15221  

我想编写一个查询,为我提供一个表格,我可以为每个组找到1级,2级,3级等。组。级别1是顶级(并且将始终存在),级别2是下一级。可以有无限级别,但此时级别8是最高级别。

Group   | Level 1   | Level 2   | Level 3   | Level 4   | Level 5  
--------+-----------+-----------+-----------+-----------+---------
S-111   | S-1       | S-11      | S-111     |           |  
S-11211 | S-1       | S-11      | S-112     | S-1121    | S-11211  
S-1211  | S-1       | S-12      | S-121     | S-1211    | 
S-1212  | S-1       | S-12      | S-121     | S-1212    | 
S-122   | S-1       | S-12      | S-122     |           |     
S-123   | S-1       | S-12      | S-123     |           |
S-1311  | S-1       | S-13      | S-131     | S-1311    | 
S-1312  | S-1       | S-13      | S-131     | S-1312    | 
S-1321  | S-1       | S-13      | S-132     | S-1321    | 
S-141   | S-1       | S-14      | S-141     |           |
S-151   | S-1       | S-15      | S-151     |           |
S-1521  | S-1       | S-15      | S-152     | S-1521    | 
S-15221 | S-1       | S-15      | S-152     | S-1522    | S-15221  

我已经使用Google和此页面来查找最终解决方案,但还没有找到它。但我设法做到这一点:

WITH MyTest as  
(  
    SELECT 
        P.PRCTR_CHILD, P.PRCTR_PARENT, 
        CAST(P.PRCTR_CHILD AS VARCHAR(MAX)) AS Level  
    FROM 
        [IBM_PA_Integration].[dbo].[PRCTRHIER] AS P  
    WHERE 
        P.PRCTR_PARENT = 'S-1000' –- S-1000 is a division  

    UNION ALL  

    SELECT 
        P1.PRCTR_CHILD, P1.PRCTR_PARENT, 
        CAST(P1.PRCTR_CHILD AS VARCHAR(MAX)) + ', ' + M.Level  
    FROM 
        [IBM_PA_Integration].[dbo].[PRCTRHIER] AS P1  
    INNER JOIN 
        MyTest M ON M.PRCTR_CHILD = P1.PRCTR_PARENT  
)  
SELECT *   
FROM MyTest  
WHERE PRCTR_PARENT  = 'FS2004' –- FS2004 is the level top level / level above S-1000  

1 个答案:

答案 0 :(得分:1)

如果您有固定或有限数量的级别,则可能不需要DYNAMIC SQL。 “解析”可以使用一点XML完成路径。

请考虑以下事项:

示例:

<Binary Id="vcredist_x862013.exe" SourceFile="D:\Projects\vcredist_x862013.exe"/>
<CustomAction Id="Launchvc2013" BinaryKey="vcredist_x862013.exe"  ExeCommand="" Execute='deferred' Return='asyncNoWait' Impersonate='no'/>
 <InstallExecuteSequence>
        <Custom Action='Launchvc2013' Before='InstallFinalize'>NOT Installed AND NOT REMOVE</Custom>
</InstallExecuteSequence>

<强>返回

enter image description here