如何按层次对行进行排序

Gle*_*leb 5 sql t-sql sql-server

我的表具有层次结构,父子关系,并希望按该层次结构对其进行排序。表是:

id|parent|type
--------------
1 |0     |1
2 |0     |1
3 |0     |1
4 |0     |2
5 |0     |2
6 |2     |2
7 |3     |2
Run Code Online (Sandbox Code Playgroud)

结果,我想要这个:

id|parent|type
--------------
1 |0     |1
2 |0     |1
6 |2     |2
3 |0     |1
7 |3     |2
4 |0     |2
5 |0     |2
Run Code Online (Sandbox Code Playgroud)

所以我想得到像树视图那样的东西,其中类型1首先排序,类型2最后排序。

现在,我尝试使用递归,但顺序错误:

with cte as
(
  select id, parent, type from tbl where id=1
  union all
  select id, parent, type,
  ROW_NUMBER()over(
   order by
         (case when t.type = 1 then 1
            when t.type = 2 then 2
    else 1000
    end) as rn
  from tbl t
  inner join cte c on c.id=t.parent
)
select * from cte
order by rn
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Ami*_*mit 6

可以使用以下递归 CTE 来完成:

WITH cte AS (
  SELECT *,
    CAST(ROW_NUMBER() OVER(ORDER BY id) AS REAL) rn,
    1 level
  FROM tbl
  WHERE parent = 0
  UNION ALL
  SELECT t2.*,
    cte.rn + (CAST(ROW_NUMBER() OVER(ORDER BY t2.id) AS REAL) / POWER(10, cte.level)) rn,
    cte.level + 1 level
  FROM tbl t2 INNER JOIN cte
    ON t2.parent = cte.id
)
SELECT id, parent, type
FROM cte
ORDER BY rn
Run Code Online (Sandbox Code Playgroud)

使用更复杂的示例数据查看SQLFiddle(更深的层次结构,“无序父子 ID”)


Eri*_*ric 3

使用 order byhierarchyid与 cte 很简单,不是测试递归关系

DECLARE @Data table (Id int identity(1,1) primary key, Parent int, Type int)

INSERT @Data VALUES 
(0, 1),
(0, 1),
(0, 1),
(0, 2),
(0, 2),
(2, 2),
(3, 2)

SELECT * FROM @Data

;WITH level AS
(
    -- The root, build the hierarchy by /{Type}.{Id}/, where Type is important then Id
    SELECT *, -- 0 AS Level,
        '/' + CONVERT(varchar(max), Type + 0.1 * Id) + '/' AS Ordering 
    FROM @Data 
    WHERE Parent = 0
    UNION ALL
    -- Connect the parent with appending the hierarchy
    SELECT d.*, -- c.Level + 1, 
        c.Ordering + CONVERT(varchar(max), d.Type + 0.1 * d.Id) + '/' 
    FROM @Data d INNER JOIN level c ON d.Parent = c.Id
)
SELECT Id, Parent, Type FROM level 
ORDER BY CAST(Ordering as hierarchyid) -- The key part to convert data type
Run Code Online (Sandbox Code Playgroud)

SQL小提琴