我有一个名为Department
的表格,其中包含3列:DepartmentID
,DepartmentName
,ParentID
。
有关详细信息,请参阅SQL Fiddle
我想按ParentID和Generation订购结果。像这样:
╔═════════╦════════════════╦════════════╦═════════ ═╗
║儿童ID║部门名称║代║亲子ID║
╠═════════╬════════════════╬════════════╬═════════ ═╣
║1║经理║0║NULL║
║6║销售额║1║1║
║7║舰队║1║1║
║4║货物║2║7║
║5║运输║2║7║
║2║IT║2║6║
║3║食物║2║6║
╚═════════╩════════════════╩════════════╩═════════ ═╝
我尝试了不同的ORDER BY
但没有效果。
我的存储过程:
WITH Hierarchy(ChildId, DeparmentName, Generation, ParentID)
AS
(
SELECT DepartmentID, DeparmentName, 0, ParentID
FROM Departments AS FirtGeneration
WHERE ParentID IS NULL
UNION ALL
SELECT NextGeneration.DepartmentID, NextGeneration.DeparmentName, Parent.Generation + 1, Parent.ChildId
FROM Departments AS NextGeneration
INNER JOIN Hierarchy AS Parent ON NextGeneration.ParentID = Parent.ChildId
)
SELECT * FROM Hierarchy
OPTION(MAXRECURSION 32767)
我使用MS SQL Server 2005
答案 0 :(得分:1)
尝试将路径存储在分层查询的顶部:
WITH Hierarchy(ChildId, DeparmentName, Generation, ParentID, Path) AS (
SELECT DepartmentID, DepartmentName, 0, ParentID,
RIGHT('000' + CAST(DepartmentID as VARCHAR(MAX)), 3) as Path
FROM Departments FirstGeneration
WHERE ParentID IS NULL
UNION ALL
SELECT NextGeneration.DepartmentID, NextGeneration.DeparmentName, Parent.Generation + 1, Parent.ChildId,
Path + '-->' + CAST(RIGHT('000' + CAST(NextGeneration.DepartmentID as VARCHAR(MAX)), 3)
FROM Departments NextGeneration INNER JOIN
Hierarchy Parent
ON NextGeneration.ParentID = Parent.ChildId
)
SELECT h.*
FROM Hierarchy h
ORDER BY path
OPTION(MAXRECURSION 32767);