We have a table containing a hierarchy of data which is account parent and children relationship so 1 parent account would have 1 to many children account.

Then we have a flag for whether account balance should be included as part of accounting calculation and the flag called INCL_COUNT.

So any account with INCL_COUNT flag should be included as part of the calculation total amount.

The problem is we have 1 parent account which has a total balance for all children on the same table so to dedup it we usually use the balance from the parent and ignore the children.

However, we found the data for the parent account has a different INCL_COUNT flag from the children (e.g. parent account has INCL_COUNT flag = 'Y' but the children account INCL_COUNT flag = 'N')

Hence now when the parent account has the flag = 'N', we need to check whether the child account have the flag 'Y' as per below example:

Code:

```
APP_ID PARENT_APP_ID BALN_A INCL_COUNT
123 3000 N - because the parent account is flagged N we would have to search the children's flag
124 123 1000 Y - we take this child because it is flagged Y and the parent is N
125 2000 Y - we take this parent because it is flagged Y
126 123 1000 Y - we take this child because it is flagged Y and the parent is N
127 125 1000 Y
128 123 1000 Y - we take this child because it is flagged Y and the parent is N
129 1000 Y
130 125 1000 Y
```

So the logic is

if the parent account is flagged Y we take the balance amount, if the parent account is flagged N we need to go through the children's flag before taking the amount.

So for the above example, the total balance amount should be 6000 (app_id children: 124+126+128 and parent: 125+129)

Any help would be greatly appreciated.