具有Desc / Asc排序的Order By子句的Case语句

时间:2014-09-20 14:33:48

标签: sql sql-server tsql

SELECT *
FROM
    TableName
WHERE
ORDER BY 
    CASE @OrderByColumn
    WHEN 1 THEN Forename
    WHEN 2 THEN Surname
    END;

我有一个如上所述的声明,让我动态选择如何订购查询结果。但是,如何指定我要订购的Forename DESC和姓氏ASC

3 个答案:

答案 0 :(得分:18)

您需要将ORDER BY拆分为两部分:

SELECT *
FROM
    TableName
WHERE
ORDER BY 
    (CASE @OrderByColumn
    WHEN 1 THEN Forename
    END) DESC -- Forename --> descending
,   (CASE @OrderByColumn
    WHEN 2 THEN Surname
    END) ASC -- Surname --> ascending

答案 1 :(得分:4)

order by中需要两个子句:

ORDER BY (CASE WHEN @OrderByColumn = 1 and @Dir = 'ASC' THEN Forename
               WHEN @OrderByColumn = 2 and @Dir = 'ASC' THEN Surname
          END) ASC,
         (CASE WHEN @OrderByColumn = 1 and @Dir = 'DESC' THEN Forename
               WHEN @OrderByColumn = 2 and @Dir = 'DESC' THEN Surname
          END) DESC

答案 2 :(得分:2)

另一个例子:

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

更多详情...... http://codechef4u.com/post/2015/04/07/order-by-clause-with-case-expressions-case-statement