I need to identify the primary channel (which is highest in hierarchy) with only one set of flag set under it's hierarchy. In below case, US is not a valid primary channel since there are two flags underneath. Only valid primary channels are US1, US2, UK.
I would like to have a solution with single query, if it's possible; otherwise I will explore options with procedure.
I tried few variations with hierarchical query, group by, count(flag), somehow I am unable to eliminate "US" and get the desired result.
I would appreciate, if someone can help me with high level approach for this use case.
Input Data
---------------------------------
channel | flag | parent channel
---------------------------------
US | |
US1 | | US
A1 | yes | US1
A2 | | A1
A3 | | A2
US2 | | US
B1 | | US2
B2 | yes | B1
B3 | | B2
UK | |
C1 | | UK
C2 | | C1
C3 | yes | C2
---------------------------------
Multiple hierarchies with flag count using the input data
---------------------
channel | flag count
---------------------
US | 2
US1 | 1
A1 | 1
A2 | 0
A3 | 0
US2 | 1
B1 | 1
B2 | 1
B3 | 0
UK | 1
C1 | 1
C2 | 1
C3 | 1
----------------
Output
---------------------------------
primary channel
---------------------------------
US1
US2
UK
---------------------------------