Clean up agg query part and make its logic more clear