• (Without going into the details of your query) maybe you can convert your query to a CTE then group the result?