首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用CTE向树数据添加排序覆盖

使用CTE向树数据添加排序覆盖
EN

Stack Overflow用户
提问于 2020-06-01 21:45:05
回答 1查看 60关注 0票数 2

我有一个目录树,它对目录名进行排序(实际上是完整的目录路径-- "root > sub1 > sub2 > my catalog")。我添加了一个"Index“列来覆盖目录中的排序。在查看单个目录的直接后缀时,我能够使它工作,但在查看整个目录树时,我无法让它工作。

代码语言:javascript
复制
dbo.Catalogs
- CatalogID (int,identity,key)
- Name
- ParentCatalogID (int - 0 for root level catalogs)
- Index (int=0, new field to override alpha sort - higher numbers should take priority)

我要获得整个目录树的查询是:

代码语言:javascript
复制
;with CatalogList as
    ( 
        -- top level catalogs
        select Catalogs.CatalogID, [Name], 
            ParentCatalogID, 1 as CatalogLevel, 
            cast([Name] as varchar(max)) as CatalogPath, Catalogs.[Index]
        from Catalogs
        where ParentCatalogID = 0           

        union all

        -- sub catalogs, building CatalogPath & CatalogLevel
        select Catalogs.CatalogID, Catalogs.[Name], 
            Catalogs.ParentCatalogID, CL.CatalogLevel + 1, 
            CL.CatalogPath + ' > ' + Catalogs.[Name] as CatalogPath, Catalogs.[Index]
        from Catalogs
        inner join CatalogList as CL on CL.CatalogID = Catalogs.ParentCatalogID
        where Catalogs.ParentCatalogID > 0
    )
select CatalogList.*
from CatalogList
order by CatalogPath

目前,这只适用于alpha排序。下面的输出需要在1665年之前实现CatalogID 1667,因为指数更高。我试着看ROW_NUMBER() OVER(PARTITION BY...),但一直没能让它正常工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-01 23:01:42

您使用row_number()在正确的路径上

示例

代码语言:javascript
复制
Declare @YourTable Table ([CatalogID] int,[Name] varchar(50),[ParentCatalogID] int,[Index] int)  
Insert Into @YourTable Values 
 (1661,'Canada',0,0)
,(1663,'All Provinces',1661,0)
,(1665,'AG Install & Leasing',1663,0)
,(1666,'Canada Multi-Use',1663,0)
,(1667,'Construnction & Forestry',1663,1)
,(1668,'Turf',1663,'')
,(1664,'Quebec Only',1661,0)

;with cteP as (
      Select CatalogID
            ,[Name]
            ,ParentCatalogID
            ,CatalogLevel = 1
            ,CatalogPath = convert(varchar(500),[Name])
            ,[Index]
            ,Seq = convert(varchar(500),concat('',10000+row_number() over (partition by ParentCatalogID order by [Index] desc,[Name])))
      From   @YourTable
      Where  ParentCatalogID =0
      Union  All
      Select r.CatalogID
            ,r.[Name]
            ,r.ParentCatalogID
            ,p.CatalogLevel + 1
            ,CatalogPath = convert(varchar(500),concat(p.CatalogPath,' > ',r.[Name]))
            ,r.[Index]
            ,Seq = convert(varchar(500),concat(p.Seq,concat('\',10000+row_number() over (partition by r.ParentCatalogID  order by r.[Index] desc,r.[Name]))))
      From   @YourTable r
      Join   cteP p on r.ParentCatalogID  = p.CatalogID
)
Select *
 From  cteP 
 Order By Seq

返回

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62141470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档