0

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

等级制度

其中 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,以便遍历是递归的?

4

1 回答 1

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
于 2015-04-16T08:54:56.810 回答