这可能不是最有效的查询,但它是最容易编码的:
declare @YourTable table (CategoryId int primary key, ParentCategoryId int , CategoryName varchar(50))
INSERT INTO @YourTable VALUES (1, null, 'SomeRoot')
INSERT INTO @YourTable VALUES (2, 1, 'SomeChild')
INSERT INTO @YourTable VALUES (3, 2, 'SomeGrandchild')
INSERT INTO @YourTable VALUES (4, 3, 'SomeGreatGrandchild')
INSERT INTO @YourTable VALUES (10, null, 'X_SomeRoot')
INSERT INTO @YourTable VALUES (20, 10, 'X_SomeChild')
INSERT INTO @YourTable VALUES (30, 20, 'X_SomeGrandchild')
Select
c1.CategoryId, c1.CategoryName, c2.CategoryName, c3.CategoryName, c4.CategoryName
From @YourTable c1
INNER JOIN @YourTable c2 On c1.CategoryId = c2.ParentCategoryId
INNER JOIN @YourTable c3 On c2.CategoryId = c3.ParentCategoryId
INNER JOIN @YourTable c4 On c3.CategoryId = c4.ParentCategoryId
WHERE c1.ParentCategoryId IS NULL
UNION
Select
c1.CategoryId, c1.CategoryName, c2.CategoryName, c3.CategoryName, NULL
From @YourTable c1
INNER JOIN @YourTable c2 On c1.CategoryId = c2.ParentCategoryId
INNER JOIN @YourTable c3 On c2.CategoryId = c3.ParentCategoryId
WHERE c1.ParentCategoryId IS NULL
UNION
Select
c1.CategoryId, c1.CategoryName, c2.CategoryName, NULL, NULL
From @YourTable c1
INNER JOIN @YourTable c2 On c1.CategoryId = c2.ParentCategoryId
WHERE c1.ParentCategoryId IS NULL
UNION
Select
c1.CategoryId, c1.CategoryName, NULL, NULL, NULL
From @YourTable c1
WHERE c1.ParentCategoryId IS NULL
ORDER BY 2,3,4,5
输出:
SortB CategoryId CategoryName CategoryName CategoryName CategoryName
----- ----------- ------------ ------------- ----------------- --------------------
1 1 SomeRoot NULL NULL NULL
2 1 SomeRoot SomeChild NULL NULL
3 1 SomeRoot SomeChild SomeGrandchild NULL
4 1 SomeRoot SomeChild SomeGrandchild SomeGreatGrandchild
1 10 X_SomeRoot NULL NULL NULL
2 10 X_SomeRoot X_SomeChild NULL NULL
3 10 X_SomeRoot X_SomeChild X_SomeGrandchild NULL
(7 row(s) affected)