我在SQL Server中有一個層次結構,有多個父級,但似乎無法獲得我需要的結果集。在SQL層次結構中顯示所有子孫級CTE
這就是我到目前爲止。
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 | <------------------------
等
可能重複的[如何從SQL表中檢索分層數據?](http://stackoverflow.com/questions/11230693/how -to-檢索分層數據-從-A-SQL的表)。查看該QA中的選定答案。可能是你正在尋找與CTE的 – 2014-11-20 16:56:23
不,這是一個標準的層次結構SQL問題,其中有很多例子。我特別需要所有鏈接(大兒童,大孫子)喜歡的問題狀態 - 請刪除重複的標誌 – 2014-11-20 16:59:45
可能重複的[Select語句返回父母和無限兒童](http://stackoverflow.com/questions/25550850/select-statement-to-return-parent-and-infinite-children) – Tanner 2014-11-20 17:00:58