Table1 has a list of items. Table2 has a list of groups the items can be associated with. Table3 is a cross-reference between 1 and 2.
The groups in table 2 are set up in hierarchical fashion.
Key ParentKey Name
1 NULL TopGroup1
2 NULL TopGroup2
3 1 MiddleGroup1
4 2 MiddleGroup2
5 3 NextGroup1
6 4 NextGroup1
7 2 MiddleGroup3
I want to be able to select from Table1 filtered by Table3.
Select Items from Table1 Where Table3.ParentKey NOT '2' or any of it's descendants.
From another post here on stack**overflow** I've been able to use CTE to identify the hierarchy.
WITH Parent AS
(
SELECT
table2.Key,
cast(table2.Key as varchar(128)) AS Path
FROM
table2
WHERE
table2.ParentKey IS NULL
UNION ALL
SELECT
TH.Key,
CONVERT(varchar(128), Parent.Path + ',' + CONVERT(varchar(128),TH.Key)) AS Path
FROM
table2 TH
INNER JOIN
Parent
ON
Parent.Key = TH.ParentKey
)
SELECT * FROM Parent
I guess this is really a two part question.
- How do you filter the above? For example, return all groups where TopGroup1 isn't in the lineage.
- How would I apply that to filtering results in the cross-referenced table1.