2016-10-04 50 views
1

我有與部門列表的數據庫中的表。 here you can look at it分層結論sql

我寫這段代碼:

WITH tree (Id, Name, Level) 
AS 
(
SELECT t.Id, t.Name, 0 AS Level 
FROM DepartmentsT AS t WHERE t.ParentId IS NULL 
UNION ALL 
SELECT d.Id, d.Name, Level+1 
FROM DepartmentsT AS d INNER JOIN tree ON tree.Id = d.ParentId 
) 

SELECT * FROM tree 

而且我得到了

this

所以這裏的問題。我怎樣才能使記錄顯示「分層次」,我的意思是孩子被展示在他們的父母之下,而不是他們現在展示的方式?現在,它們按照它們的嵌套級別排序,而簡單的ORDER BY並不能解決問題。希望你的幫助。

WITH tree (Id, Name, Level, parents) AS (
     SELECT t.Id, t.Name, 0 AS Level, 
      cast(t.id as varchar(max)) as parents 
     FROM DepartmentsT t 
     WHERE t.ParentId IS NULL 
     UNION ALL 
     SELECT d.Id, d.Name, Level+1, 
      tree.parents + '-->' + cast(d.id as varchar(max)) 
     FROM DepartmentsT d INNER JOIN 
      tree 
      ON tree.Id = d.ParentId 
    ) 
SELECT id, name, level 
FROM tree 
ORDER BY parents; 

注:

回答

0

爲您遍歷樹可以保留此信息,這是假定的ID都是一樣的長度。

+0

謝謝你的回答,只是改變了ID給父母,它的工作! – Gelo