在SQL Server 2005中排序分层查询

fra*_*sek 7 sql-server sql-server-2005 hierarchical common-table-expression

我有以下问题:我有一个用于维护分层数据的表.我想在SQL 2005中使用CTE.

WITH tree (id, parentid, code, name) AS
(
    SELECT id, ofs.ParentID, ofs.code, ofs.name
      FROM OrganizationFeatures ofs
     WHERE ofs.ParentID IS NULL

    UNION ALL

    SELECT ofs.id, ofs.ParentID, ofs.code, ofs.name
      FROM OrganizationFeatures ofs
      JOIN tree ON tree.ID = ofs.ParentID
)

select * from tree
Run Code Online (Sandbox Code Playgroud)

但我想按代码排序,结果如下:

1
1/1
1/1/1
1/1/2
1/2/1
1/2/2
2
4/1
Run Code Online (Sandbox Code Playgroud)

等任何想法?

Lok*_*oki 4

要获取连接值,您需要在 with 中执行此操作。

要排序,您需要在最后一个选择中添加排序依据。

WITH tree (id, parentid, code, name) AS
(
    SELECT id, ofs.ParentID, ofs.code, ofs.name
      FROM OrganizationFeatures ofs
     WHERE ofs.ParentID IS NULL

    UNION ALL

    SELECT ofs.id, ofs.ParentID, tree.code+'/'+ofs.code, ofs.name
      FROM OrganizationFeatures ofs
      JOIN tree ON tree.ID = ofs.ParentID
)

select * from tree order by code
Run Code Online (Sandbox Code Playgroud)

另外,如果代码不是 varchar,则必须转换这段代码 ( tree.code+'/'+ofs.code) 中的代码列才能正常工作。