分层结论sql

时间:2016-10-04 17:08:23

标签: sql sql-server

我有数据库中的表和部门列表。 here you can look at it

我写了这段代码:

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无法解决问题。希望得到你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以在遍历树时保留此信息:

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;

注意:这假设id的长度都相同。