绑定多父层次结构

时间:2015-04-16 06:41:57

标签: sql-server parent-child hierarchy recursive-query dimensional

我有一个表格,其中保留了一些分支和层次结构的信息。信息不是以可以在维度建模中使用的方式存储的,因此在经过多次转换和提取后,我最终得到了这个:

Hierarchy

其中n0是第一级,n11是最高级别。 问题是层次结构不能像这样遍历:

SELECT 
    distinct 
        nelem.Element n0,
        primul.Element n1,
        doilea.Element n2, 
        treilea.Element n3,
        patrulea.Element n4 

FROM 
    [MIS].[dbo].[BedrockImportBST] nelem
    left join  [BedrockImportBST] primul on primul.Element=nelem.Value1 and primul.LineType in ('e','p')
    left join  [BedrockImportBST] doilea on doilea.Element=primul.Value1 and doilea.LineType in ('e','p')
    left join  [BedrockImportBST] treilea on treilea.Element=doilea.Value1 and treilea.LineType in ('e','p')
    left join  [BedrockImportBST] patrulea on patrulea.Element=treilea.Value1 and patrulea.LineType in ('e','p')

是否可以为此解决方案分配父子关系ID,以便遍历将被递归?

1 个答案:

答案 0 :(得分:1)

然后,只是为了将平面数据转换为父子层次结构,您可以使用下面的简单联合生成唯一ID(我使用FlatHierarchy作为表的名称)。我看到一个特定的元素可以出现在多个级别上,并且可以有不同的父级,这看起来有点奇怪,但是这里有:

DECLARE @IDS TABLE
(
    ID INT IDENTITY (1,1) NOT NULL,
    Label varchar(50)
)
INSERT INTO @IDS (Label)
SELECT n0
FROM FlatHierarchy
UNION 
SELECT n1
FROM FlatHierarchy
UNION 
SELECT n2
FROM FlatHierarchy
UNION 
SELECT n3
FROM FlatHierarchy
UNION 
SELECT n4
FROM FlatHierarchy
UNION 
SELECT n5
FROM FlatHierarchy
.....
UNION 
SELECT n11
FROM FlatHierarchy


SELECT i.ID, parent.ID ParentID, i.Label
FROM @IDS i
INNER JOIN FlatHierarchy f ON i.Label = f.n0
LEFT JOIN @IDS parent ON f.n1 = parent.Label
UNION 
SELECT i.ID, parent.ID ParentID, i.Label
FROM @IDS i
INNER JOIN FlatHierarchy f ON i.Label = f.n1
LEFT JOIN @IDS parent ON f.n2 = parent.Label
UNION 
SELECT i.ID, parent.ID ParentID, i.Label
FROM @IDS i
INNER JOIN FlatHierarchy f ON i.Label = f.n2
LEFT JOIN @IDS parent ON f.n3 = parent.Label
UNION 
SELECT i.ID, parent.ID ParentID, i.Label
FROM @IDS i
INNER JOIN FlatHierarchy f ON i.Label = f.n3
LEFT JOIN @IDS parent ON f.n4 = parent.Label
UNION 
SELECT i.ID, parent.ID ParentID, i.Label
FROM @IDS i
INNER JOIN FlatHierarchy f ON i.Label = f.n4
LEFT JOIN @IDS parent ON f.n5 = parent.Label
.....
UNION 
SELECT i.ID, parent.ID ParentID, i.Label
FROM @IDS i
INNER JOIN FlatHierarchy f ON i.Label = f.n10
LEFT JOIN @IDS parent ON f.n11 = parent.Label