0

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

我已经用递归CTE设置了这个样本SQL Fiddle,但我现在头脑不清。

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

因此,对于第1行,这将是零,而对于行2,3和4,这将类似地,对于行5,6,7,这将被设置为5。

回答

3

修改您的设置被设置为2。 SQL小提琴,我想出了:

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 
+0

不错,谢谢本 – Boycs