I have a problem to order by a dynamic value when I use AVG or COUNT with SQL Server. How can I make it work?
ALTER PROCEDURE GetEmployee
@SortOrder INT
AS
SELECT name,
AVG(salary) AS avgSalary,
COUNT(employeeID) AS employeeCount
FROM employee
ORDER BY CASE WHEN @SortOrder = 1 THEN avgSalary
WHEN @SortOrder = 2 THEN employeeCount
ELSE name
END
This will probably work, and is basically a quick workaround for the fact that all expressions in a
CASEstatement should be coerce-able to the same time.