Following on from my earlier question here Case statement for Order By clause with Desc/Asc sort I have a statement like this:
SELECT * FROM TableName WHERE ORDER BY CASE @OrderByColumn WHEN 1 THEN Forename END DESC, CASE @OrderByColumn WHEN 2 THEN Surname END ASC
This works well, but sometimes I need more than column in the order by. I actually need something like this:
..... ORDER BY CASE @OrderByColumn WHEN 1 THEN Forename, Date, Location END DESC
I can't work out how to make the CASE
statement allow multiple columns in the THEN
part.
Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first. The column that is entered at first place will get sorted first and likewise.
ORDER BY clause is used to sort the returned records in an order. By using ORDER BY clause, we can sort the result in ascending or descending order. This clause can be used with multiple columns as well.
How to use CASE with ORDER BY clause in SQL Server? To do this, we use the CASE after ORDER BY and then checks for column value. In above case, all records having Active = 1 is sorted on “Active ASC” order. All records having Active = 0 is sorted on 'LastName DESC' else 'FirstName DESC' order.
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
You can write multiple cases, even if they all have the same condition.
ORDER BY CASE @OrderByColumn WHEN 1 THEN Forename END DESC, CASE @OrderByColumn WHEN 1 THEN Date END, CASE @OrderByColumn WHEN 1 THEN Location END, CASE @OrderByColumn WHEN 2 THEN Surname END ASC
Actually, you don't specify a column to sort by, but an expression.
The case statement returns null if the condition is not met, so actually it means:
CASE @OrderByColumn WHEN 1 THEN Forename ELSE NULL END
So if @OrderByColumn is not 1 then the statement returns always NULL. That doesn't exclude it from sorting, by the way, but it puts all those rows together in the result, making 'SurName' the decisive sorting within that group of rows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With