首页 > 解决方案 > 使用递归 SQL 创建自然层次顺序

问题描述

我有一个表格,其中包含具有内部父子关系的类别。

该表如下所示:

ID | ParentID | OrderID
---+----------+---------
1  | Null     | 1
2  | Null     | 2
3  | 2        | 1
4  | 1        | 1

OrderID是当前级别内的订单。

我想创建一个递归 SQL 查询来创建表的自然顺序。

这意味着输出将类似于:

ID   |  Order
-----+-------
1    | 100
4    | 101
2    | 200
3    | 201

感谢任何帮助。

谢谢

标签: sqlsql-serverrecursioncommon-table-expression

解决方案


我不太确定您所说的“自然顺序”是什么意思,但以下查询会为此数据生成您想要的结果:

with t as (
      select v.*
      from (values (1, NULL, 1), (2, NULL, 2), (3, 2, 1), (4, 1, 1)) v(ID, ParentID, OrderID)
     )
select t.*,
       (100 * coalesce(tp.orderid, t.orderid) + (case when t.parentid is null then 0 else 1 end)) as natural_order
from t left join
     t tp
     on t.parentid = tp.id
order by natural_order;

推荐阅读