需要在每个级别按名称排序层次结构

时间:2015-07-03 09:14:05

标签: sql treeview

我们在表中有四列ID(int),parentID(int),Hierarchy(int),Name。需要获取这个按名称排序的树结构, 例如

表格看起来像

parentID ID Hierarchy  Name 
NULL     1      1       World
4        3      3       Bombay
1        4      2       Asia
1        6      2       Europe
1        7      2       Australia
7        8      3       Sydney
7        9      3       Melbourne 

能够得到这个

parentID ID Hierarchy  Name 
NULL     1      1       World
1        4      2       Asia
4        3      3       Bombay
1        6      2       Europe
1        7      2       Australia
7        8      3       Sydney
7        9      3       Melbourne

想要输出

parentID ID Hierarchy  Name 
NULL     1      1       World
1        4      2       Asia
4        3      3       Bombay
1        7      2       Australia
7        9      3       Melbourne
7        8      3       Sydney
1        6      2       Europe

能够像第二个表那样进行排序,但却被卡住以按名称维护树结构进行排序

我的查询

 ;WITH Level_CTE AS 
(
SELECT 
ParentID, ID, Hierarchy,Name, 0 AS Lvl,CAST(ID AS VARCHAR(255)) AS Path
FROM Level
WHERE ParentID is null

UNION ALL

SELECT 
O.ParentID, O.ID, O.Hierarchy,O.Name,Lvl + 1 Lvl, CAST(Path + '.' + CAST(o.ID AS VARCHAR(255)) AS VARCHAR(255)) AS Path
FROM Level O
JOIN Level_CTE zol_CTE
ON O.ParentID = zol_CTE.ID
)

select * into #tempHierarchy from Level_CTE

select * from #tempHierarchy order by Path

- 请在这里帮忙

2 个答案:

答案 0 :(得分:0)

H个

;WITH Level_CTE AS 
(
SELECT 
ParentID, ID, Hierarchy,Name, 0 AS Lvl,CAST(ID AS VARCHAR(255)) AS Path
FROM Level
WHERE ParentID is null

UNION ALL

SELECT 
O.ParentID, O.ID, O.Hierarchy,O.Name,Lvl + 1 Lvl, CAST(Path + '.' + CAST(o.ID AS VARCHAR(255)) AS VARCHAR(255)) AS Path
FROM Level O
JOIN Level_CTE zol_CTE
ON O.ParentID = zol_CTE.ID
)
select * into #tempHierarchy from Level_CTE



select * from #tempHierarchy ORDER BY REPLACE(path,'.','')

我得到的结果如下

ParentID    ID  Hierarchy   Name    Lvl Path
==============================================
NULL        1   1       World       0   1
1           4   2       Asia        1   1.4
4           3   3       Bombay      2   1.4.3
1           6   2       Europe      1   1.6
1           7   2       Australia   1   1.7
7           8   3       Sydney      2   1.7.8
7           9   3       Melbourne   2   1.7.9

让我知道我将为您重新构建的更改。

由于

答案 1 :(得分:0)

最后通过在路径列中用name替换id来获得它。 !!之前是如此愚蠢!