Given the following recursive query:
WITH DepartmentHierarchy (DepartmentID, Name, IsInactive, IsSpecial, ParentId, HierarchyLevel) AS
(
-- Base case
SELECT
DepartmentId,
Name,
IsInactive,
IsSpecial,
ParentId,
1 as HierarchyLevel
FROM StoreDepartment
WHERE ParentId IS NULL
UNION ALL
-- Recursive step
SELECT
d.DepartmentId,
d.Name,
d.IsInactive,
d.IsSpecial,
d.ParentId,
dh.HierarchyLevel + 1 AS HierarchyLevel
FROM StoreDepartment d
INNER JOIN DepartmentHierarchy dh ON
d.ParentId = dh.DepartmentId
) SELECT * FROM DepartmentHierarchy
I am able to select data which looks like this:
DepartmentId, Name, IsInactive, IsSpecial, ParentId, HeirarchyLevel
1, Store, 0, 0, NULL, 1
2, Main Department 1, 0, 1, 2
3, Main Department 2, 0, 1, 2
4, Sub For Main 1, 0, 2, 3
Also, assume a table exists with DepartmentId and ItemId (ex: DepartmentItemRelationship). Leaf nodes from the department heirarchy are paired with items here.
I want my recursive query to only return nodes (at any level) that have at least one leaf node below them with an match in the department/item relationship table. These nodes could be 6 or 7 levels down, so I'm not sure how I would amend my query to be sure to include those.
Thanks, Kyle