Btw, the formala for calculating the CityPages needs a re-touch due to your integer division.SELECT City, COUNT(*) AS TotalMembers, CASE WHEN COUNT(*) % 20 = 0 THEN COUNT(*) / 20 ELSE 1 + COUNT(*) / 20 END AS CityPagesFROM tblUserDetailsWHERE City NOT IN ('', '-') AND Active = 1GROUP BY CityHAVING COUNT(*) > 50ORDER BY COUNT(*) DESCAnd with that in place, we can easily write a function for this.CREATE FUNCTION dbo.fnGetCityPages()RETURNS INTASBEGIN RETURN ( SELECT SUM(CityPages) FROM ( SELECT TOP 50 CASE WHEN COUNT(*) % 20 = 0 THEN COUNT(*) / 20 ELSE 1 + COUNT(*) / 20 END AS CityPages FROM tblUserDetails WHERE City NOT IN ('', '-') AND Active = 1 GROUP BY City HAVING COUNT(*) > 50 ORDER BY COUNT(*) DESC ) AS d )END
E 12°55'05.63"N 56°04'39.26"