【问题标题】:Recursive CTE SQL Query Help Needed需要递归 CTE SQL 查询帮助
【发布时间】:2013-03-31 09:58:42
【问题描述】:

我正在使用 SQL Server 2012,需要编写一个递归 SQL 查询来遍历层次结构(在同一个表上),以返回一个在其元组上具有特定条件的父级。

我已经使用递归 CTE 设置了这个示例 SQL Fiddle,但我现在已经不知所措了。

我需要的是能够返回第四列 (ReportingLocationId int),它被定义为具有 IsReportingRollup bit 集的层次结构的父 ID。

所以对于第 1 行,这将为空,对于第 2、3 和 4 行,这将被设置为 2。类似地,对于第 5、6、7 行,这将被设置为 5。

【问题讨论】:

    标签: sql-server sql-server-2012 common-table-expression recursive-query


    【解决方案1】:

    修改您提供的 SQL Fiddle,我想出了:

    WITH hierarchy AS (
      SELECT t.Id,
             t.Name,
             t.ParentId,
             CAST(NULL AS nvarchar(100)) AS parentname,
             case when t.IsReportingRollup = 1 then t.Id
                  else null
             end as ReportingLocationId
        FROM Location t
       WHERE t.ParentId IS NULL
      UNION ALL
      SELECT x.Id,
             x.Name,
             x.ParentId,
             y.Name,
             case when y.ReportingLocationId is not null then y.ReportingLocationId
                  when x.IsReportingRollup = 1 then x.Id
                  else null
             end
        FROM Location x
        JOIN hierarchy y ON y.Id = x.ParentID)
    SELECT s.Id,
           s.Name,
           s.parentname,
           s.ReportingLocationId
      FROM hierarchy s
    

    【讨论】: