declare @demo table
(
SectionId int not null primary key clustered
, ParentId int null --foreign key references @demo(SectionId)
, DatumId int
);
insert @demo
select 1, null, 1
union select 2, 1, 2
union select 3, 1, 3
union select 4, 2, 4
union select 5, null, 5
union select 6, 5, 6
;
with demoHierarchy
as
(
select SectionId
, SectionId ParentId
, SectionId OriginalAncestorId
, DatumId
from @demo
where ParentId is null --remove this line if you want OriginalAncestorId to be AnyAncestorId (if that doesn't make sense, try it and see)
union all
select d.SectionId
, d.ParentId
, h.OriginalAncestorId
, d.DatumId
from @demo d
inner join demoHierarchy h
on d.ParentId = h.SectionId
where d.ParentId is not null --implied by the join, but here to make it explicit
)
select OriginalAncestorId SectionId
, DatumId
from demoHierarchy
where OriginalAncestorId = 1 --not needed given your sample data only contains this data, but required when you have multiple root ancestors
階層クエリの詳細については、http://blog.sqlauthority.com/2012/04/24/sql-server-introduction-to-hierarchical-query-using-a-recursive-cte-a-primer/を参照してください。