表中的层次结构的自联接

时间:2018-03-12 19:26:17

标签: sql sql-server tsql stored-procedures common-table-expression

我有一个名为层次结构的表,其中包含子列和父列,如下所示

childid  parentid
53047    52915
52915    52914
52914    53037
52914    91856
53037    161212
91856    161212(great great grandparent of 53047)

我有另一个名为Names的表,其中包含location_idname列。 Location_id具有层次结构表中子级和父级的所有值。现在我想获取id 53047的所有父,祖父母和伟大的名字。我的输出应该如下所示:

childid childname parentname grandparentname greatgrandparentname
53047  Strasbourg  Bas-Rhin   Alsace                France

1 个答案:

答案 0 :(得分:0)

我将答案放在https://sqleditor.net/q/BkVQc9Etf

-- YOUR ANSWER
;WITH cte AS ( 
  SELECT childid, parentid
  , (select name from Names where location_id = childid) AS child_name
  , (select name from Names where location_id = parentid) AS parent_name
  FROM hierarchy
  WHERE childid = 53047
  UNION ALL
  SELECT hierarchy.childid, hierarchy.parentid
  , (select name from Names where location_id = hierarchy.childid) AS child_name
  , (select name from Names where location_id = hierarchy.parentid) AS parent_name
  FROM hierarchy inner join cte on hierarchy.childid = cte.parentid
)
--pivot
SELECT 53047 AS childid, 
(SELECT name from Names where location_id = 53047) AS childname,
[1] AS parentname, [2] AS grandparentname, [3] AS greatgrandparentname, [4] AS greatgreatgrandparentname, [5] AS greatgreatgreatgrandparentname
FROM
(
   -- prepare the data set
    SELECT 
    RANK() OVER   
        (ORDER BY parentid) AS Rank, parent_name
    FROM
    (
        SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS id, childid, parentid, child_name, parent_name
        FROM cte
    ) Z
) Y
PIVOT
(
  MAX(parent_name)
  FOR Rank IN ([1], [2],[3], [4],[5])
) AS pvt;

https://sqleditor.net/q/BkVQc9Etf