当我在SQL Server中使用AVG或COUNT时,我有一个动态值订购的问题。我怎样才能使它发挥作用?
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
答案 0 :(得分:1)
这可能会有效,并且基本上是一个快速的解决方法,因为CASE
语句中的所有表达式都应该同时强制执行。
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 AVG(salary) END,
CASE WHEN @SortOrder = 2 THEN COUNT(employeeID) END,
CASE WHEN @SortOrder NOT IN (1, 2) THEN name END