自定义层次结构

Custom hierarchy

我有一个table来源

idGeo     GEO   PARENTID
1   EMEA    NULL
2   France  1
3   mIDCAPSfRANCE   2
4   Germany 1
5   France exl midcaps  2
6   Amercias    NULL
7   US  6

层次结构的预期结果

我尝试进行左连接(自连接),但无法完全按照预期进行。

据我了解,您希望随着关卡的进行生成列。 您不能动态生成列,SQL 是一种固定的列语言。

这是一个通用的方法,不管层次结构的级别。

SQL

-- DDL and sample data population, start
DECLARE @tbl table (
    idGeo INT IDENTITY PRIMARY KEY,
    GEO   VARCHAR(64),
    PARENTID INT
);

insert into @tbl (GEO, PARENTID) values 
(   'EMEA',    NULL),
(   'France',  1),
(   'mIDCAPSfRANCE',   2),
(   'Germany', 1),
(   'France exl midcaps',  2),
(   'Amercias',    NULL),
(   'US',  6);
-- DDL and sample data population, end

--SELECT * FROM @tbl;

WITH cte AS 
(
    -- Anchor query
    SELECT idGEO, GEO, ParentID, 1 AS [Level]
        , CAST('/' + GEO AS VARCHAR(1000)) AS XPath
    FROM @tbl
    WHERE ParentID IS NULL
    UNION ALL
    -- Recursive query
    SELECT t.idGEO, t.GEO, t.ParentID, cte.[Level] + 1 AS [Level]
        , CAST(cte.[XPath] + '/' +  t.GEO AS VARCHAR(1000)) AS [XPath]
    FROM @tbl AS t
        INNER JOIN cte ON t.ParentID = cte.idGEO
    WHERE t.ParentID IS NOT NULL 
)
SELECT idGEO
    , REPLICATE('  ',[Level]-1) + GEO AS GEOHierarchy
    , GEO, ParentID, [Level], [XPath]
FROM cte
ORDER BY XPath;

输出