Yes, you can use dynamic SQL to achieve what you desire. First, create a variable to hold the name of the column that will vary. Then, create another variable to hold the dynamically generated query. Finally, use sp_executesql
to run this dynamic query. The code will look something like this:
declare @colname varchar(50) = ''
declare @query nvarchar(8000) = 'INSERT INTO @temp (ranking,item,groupCount,groupName)'
+ 'SELECT RANK() OVER(ORDER BY COUNT(*) desc,' + @colname + ') [Rank],' + @colname
+ '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 ' + @colname
+ ' ORDER BY groupCount desc, ' + @colname
execute sp_executesql @query