修改您提供的 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