sql-server – SQL Server 2005中的SORTING分层查询

我有以下问题:我有一个用于维护分层数据的表.我想在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.name
      FROM OrganizationFeatures ofs
      JOIN tree ON tree.ID = ofs.ParentID
)

select * from tree

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

1
1/1
1/1/1
1/1/2
1/2/1
1/2/2
2
4/1

等任何想法?

解决方法

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

要进行排序,您需要在最后一次选择中添加订单.

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

select * from tree order by code

此外,如果代码不是varchar,则必须转换此代码(tree.code’/’ofs.code)中的代码列才能使其工作.

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...