【问题标题】:SORTING Hierarchical Queries in SQL Server 2005在 SQL Server 2005 中对分层查询进行排序
【发布时间】:2010-10-03 04:07:30
【问题描述】:

我有以下问题:我有一个用于维护分层数据的表。我想使用 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

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

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

等等。有任何想法吗?

【问题讨论】:

    标签: sql-server sql-server-2005 common-table-expression hierarchical


    【解决方案1】:

    要获取连接的值,需要在 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
    

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

    【讨论】:

      【解决方案2】:

      Loki,我有类似的查询,但它没有按我想要的名称排序,而是按代码排序 - 这是星期五,我超载了。

      无论如何,运行您的查询给了我一个错误,有必要强制转换;我不得不按照以下方式更改它:

      WITH tree (id, parentid, name, code) AS
      (
          SELECT id, ofs.ParentID, ofs.name, CAST(ofs.name as varchar(255))
            FROM OrganizationFeatures ofs
           WHERE ofs.ParentID IS NULL
      
          UNION ALL
      
          SELECT ofs.id, ofs.ParentID, ofs.name, CAST(tree.code+'/'+ofs.name as varchar(255))
            FROM OrganizationFeatures ofs
            JOIN tree ON tree.ID = ofs.ParentID
      )
      
      select * from tree order by code
      

      问题在于,尽管名称是 varchar,但仍需要强制转换为 varchar。很可能 varchar(255) 不足以处理大树。

      所以我做了一个上面提到的问题不是那么大的版本:

      WITH tree (id, parentid, name, code) AS
      (
          SELECT id, ofs.ParentID, ofs.name, 
                 CAST(ROW_NUMBER() OVER (ORDER BY ofs.name ASC) as varchar(255)) 
            FROM OrganizationFeatures ofs
           WHERE ofs.ParentID IS NULL
      
          UNION ALL
      
          SELECT ofs.id, ofs.ParentID, ofs.name, 
                 CAST(tree.code +'/' + CAST(ROW_NUMBER() OVER (ORDER BY ofs.name ASC) as varchar(255)) as varchar(255))
            FROM OrganizationFeatures ofs
            JOIN tree ON tree.ID = ofs.ParentID
      )
      
      select * from tree order by code
      

      但我不喜欢这种需要强制转换的解决方案。有没有更好的解决方案?

      【讨论】:

        猜你喜欢
        • 2010-09-19
        • 1970-01-01
        • 2010-09-18
        • 1970-01-01
        • 2023-04-09
        • 2011-04-05
        • 1970-01-01
        • 2010-11-03
        相关资源
        最近更新 更多