I have a table in SQL Server in which I need to select the data, sorted based on a value. For example,
If the sort value is 1, then I need to sort by column1, column2 and then column3.
If the sort value is 2, then I need to sort by column2, column1 and then column3.
If the sort value is 3, then I need to sort by column3, column1 and then column2.
Can anyone tell me how can I achieve this in SQL without using if else as below:
IF @SortOrder = 1
THEN
SELECT *
FROM table
ORDER BY c1, c2, c3
END
IF @SortOrder = 2
THEN
SELECT *
FROM table
ORDER BY c2, c1, c3
END
IF @SortOrder = 3
THEN
SELECT *
FROM table
ORDER BY c3, c1, c2
END
You can use CASE EXPRESSION
for conditional ordering:
SELECT * FROM Table
ORDER BY CASE WHEN @SortOrder = 1 then c1
WHEN @SortOrder = 2 then c2
ELSE c3
END,
CASE WHEN @SortOrder = 1 then c2
ELSE c1
END,
CASE WHEN @SortOrder in(1,2) then c3
ELSE c2
END