Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case statement for Order By clause with Desc/Asc sort

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

I have a statement like above which lets me dynamically choose how to order the results of a query. However, how do I specify that I want the Forename ordered DESC and the Surname ASC?

like image 737
volume one Avatar asked Sep 20 '14 14:09

volume one


3 Answers

You need to split your ORDER BY in two parts:

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
like image 112
Sergey Kalinichenko Avatar answered Nov 17 '22 00:11

Sergey Kalinichenko


You need two clauses in the 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
like image 25
Gordon Linoff Avatar answered Nov 16 '22 23:11

Gordon Linoff


another example:

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

more details ...http://codechef4u.com/post/2015/04/07/order-by-clause-with-case-expressions-case-statement

like image 3
nagnath Avatar answered Nov 16 '22 23:11

nagnath