我需要以特定方式获得树的有序层次结构。所讨论的表看起来有点像这样(所有ID字段uniqueidentifiers,我已经简化数据例如起见):CTE递归获取树层次结构
EstimateItemID EstimateID ParentEstimateItemID ItemType -------------- ---------- -------------------- -------- 1 A NULL product 2 A 1 product 3 A 2 service 4 A NULL product 5 A 4 product 6 A 5 service 7 A 1 service 8 A 4 product
树结构的图形视图(*表示“服务”):
A ___/ \___ / \ 1 4 /\ /\ 2 7* 5 8 / / 3* 6*
使用此查询,我可以得到层级(假装“A”是唯一标识符,我知道这是不是在现实生活中):
DECLARE @EstimateID uniqueidentifier
SELECT @EstimateID = 'A'
;WITH temp as(
SELECT * FROM EstimateItem
WHERE EstimateID = @EstimateID
UNION ALL
SELECT ei.* FROM EstimateItem ei
INNER JOIN temp x ON ei.ParentEstimateItemID = x.EstimateItemID
)
SELECT * FROM temp
这给了我EstimateID的孩子'A',但是在它出现在表格中的顺序。即:
EstimateItemID -------------- 1 2 3 4 5 6 7 8
不幸的是,我需要的是遵循以下限制的结果集的排序层次:
1. each branch must be grouped 2. records with ItemType 'product' and parent are the top node 3. records with ItemType 'product' and non-NULL parent grouped after top node 4. records with ItemType 'service' are bottom node of a branch
所以,为了我需要的结果,在这个例子中,是:
EstimateItemID -------------- 1 2 3 7 4 5 8 6
我需要添加到我的查询来完成此操作?
辉煌。这已经有几年了,但今天发现它很有用。然而,原谅说,我发现在原来的帖子中提供的例子很难让我转化为更常见的解决方案。所以,我使用更常见的数据,表格名称和字段来重新发布您的(伟大的)想法,以便其他人更容易遵循。 – ptownbro
有没有什么办法可以通过ItemType的级别0进行排序,并且层次结构应该保持原样? –