Hi, I have a problem with my query and dynamic order by for a aggregate column. It works perfectly fine when I use the case statement for a group by column but as soon as I add a case for the aggregate column it results in an error. CREATE TABLE #Programms( ProgrammId INT, Title NVARCHAR(50))INSERT INTO #Programms VALUES(1, '2007 Ratings')CREATE TABLE #Ratings( RatingId INT, ProgrammId INT, EmployeeId INT )INSERT INTO #Ratings VALUES (1, 1, 665 )INSERT INTO #Ratings VALUES (2, 1, 321 )INSERT INTO #Ratings VALUES (3, 1, 3145 )INSERT INTO #Ratings VALUES (4, 1, 64215 )INSERT INTO #Ratings VALUES (5, 1, 632165 )INSERT INTO #Ratings VALUES (6, 1, 66325 )DECLARE @p_SortDir NVARCHAR(4)SET @p_SortDir = 'desc'DECLARE @p_SortColumn NVARCHAR(10)SET @p_SortColumn = 'Inuse' SELECT p.ProgrammId, p.Title, CAST(CASE COUNT(r.RatingId) WHEN 0 THEN 0 ELSE 1 END AS BIT) AS InUse FROM #Programms p LEFT JOIN #Ratings r ON p.ProgrammId = r.ProgrammId GROUP BY p.ProgrammId, p.TitleORDER BY CASE @p_SortDir WHEN 'desc' THEN CASE @p_SortColumn WHEN 'ProgrammId' THEN p.ProgrammId END END DESC-- Uncommenting the code block below results in an error --> Invalid column name 'InUse'./* , CASE @p_SortDir WHEN 'desc' THEN CASE @p_SortColumn WHEN 'InUse' THEN InUse END END DESC*/-- But this worksSELECT p.ProgrammId, p.Title, CAST(CASE COUNT(r.RatingId) WHEN 0 THEN 0 ELSE 1 END AS BIT) AS InUse FROM #Programms p LEFT JOIN #Ratings r ON p.ProgrammId = r.ProgrammId GROUP BY p.ProgrammId, p.TitleORDER BY inUse
Is it just not possible to use a dynamic order by for a aggregate column or am I doing something wrong here.Your help is very much appreciated!Limbic