我有一个名为层次结构的表,其中包含子列和父列,如下所示
childid parentid
53047 52915
52915 52914
52914 53037
52914 91856
53037 161212
91856 161212(great great grandparent of 53047)
我有另一个名为Names
的表,其中包含location_id
和name
列。 Location_id
具有层次结构表中子级和父级的所有值。现在我想获取id 53047的所有父,祖父母和伟大的名字。我的输出应该如下所示:
childid childname parentname grandparentname greatgrandparentname
53047 Strasbourg Bas-Rhin Alsace France
答案 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;