I don't understand the problem. I attached a testcase example that implements what you described in a more testable fashion. For now I just inspected the query but couldn't find anything wrong with it.