As I have already mentioned in comments section, Dynamic Sql has its own scope, any variable declared outside of that scope arent visible to dynamic sql, Your have to declare the variable inside your dynamic sql. Something like as follows....
SET @sql = N' DECLARE @temp AS TABLE
(
ranking int,
item nvarchar(100),
groupCount int,
groupName nvarchar(100)
)
INSERT INTO @temp
(
ranking,
item,
groupCount,
groupName
)
SELECT RANK() OVER(ORDER BY COUNT(*) desc, policy) [Rank],
' + @selection + ',
COUNT(*) AS groupCount,
''currentMonth'' AS groupName
FROM Log_PE
WHERE CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), GETDATE(), 112) + ''01'', 112)
GROUP BY ' + @selection + '
ORDER BY groupCount desc, ' + @selection + '