我在 SQL Server 中有一个层次结构,其中有多个父级,但似乎无法获得所需的结果集。
到目前为止,这就是我所拥有的。
但是我也希望有祖父母、曾祖父母、高祖父母等(等等):
到目前为止,这就是我所拥有的。
DECLARE @Table TABLE (ChildId varchar(max), ParentId varchar(max))
INSERT INTO @Table (ChildId,ParentId)
VALUES
('England',NULL),
('Cities',NULL),
('Towns',NULL),
('South West','England'),
('Bristol','South West'),
('Bristol','Cities'),
('Suburb','Bristol'),
('Thornbury','South West'),
('Thornbury','Towns');
WITH CTE (ChildId, ParentId, Level)
AS (
SELECT
ChildId,
ParentID,
0
FROM @Table
WHERE ParentID IS NULL
UNION ALL
SELECT
r.ChildId,
r.ParentId,
ct.Level + 1
FROM @Table r
JOIN CTE ct
ON ct.ChildId = r.ParentId
)
SELECT * FROM CTE order by childId, level
这将给我以下结果集:
ChildId | ParentId | Level
Bristol | Cities | 1
Bristol | South West | 2
Suburb | Bristol | 2
Suburb | Bristol | 3
Cities | NULL | 0
England | NULL | 0
South West | England | 1
Thornbury | Towns | 1
Thornbury | South West | 2
Towns | NULL | 0
但是我也希望有祖父母、曾祖父母、高祖父母等(等等):
ChildId | ParentId | Level
Bristol | Cities | 1
Bristol | South West | 2
Bristol | England | <------------------------
Suburb | South West | <------------------------
Suburb | England | <------------------------
Suburb | Cities | <------------------------
etc.