resolving bug in CTE part of stats query