使用子查询按案例排序

时间:2012-02-04 10:28:40

标签: sql-server sql-server-2008 subquery sql-order-by

当我在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

1 个答案:

答案 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