I want to Order a SQL Select Query where there\'s 2 fields that are in the order by. I then need to decide if one is Descending and the other as Ascending. How is this done<
SELECT
Customer_ID,
Name,
Age
FROM
#Customer
ORDER BY
CASE WHEN @field = 'Name' AND @direction = 'A' THEN Name ELSE NULL END ASC,
CASE WHEN @field = 'Name' AND @direction = 'D' THEN Name ELSE NULL END DESC,
CASE WHEN @field = 'Age' AND @direction = 'A' THEN Age ELSE NULL END ASC,
CASE WHEN @field = 'Age' AND @direction = 'D' THEN Age ELSE NULL END DESC
I wouldn't want to do that over many different combinations though. If you have a lot of combinations I'd do somethign based on the following...
SELECT
Customer_ID,
Name,
Age
FROM
(
SELECT
Customer_ID,
Name,
ROW_NUMBER() OVER (ORDER BY Name) AS "name_order",
Age,
ROW_NUMBER() OVER (ORDER BY Age) AS "age_order"
FROM
#Customer
)
AS [data]
ORDER BY
CASE @field1
WHEN 'Name' THEN CASE @direction1 WHEN 'A' THEN name_order ELSE -name_order END
WHEN 'Age' THEN CASE @direction1 WHEN 'A' THEN age_order ELSE -age_order END
ELSE NULL
END,
CASE @field2
WHEN 'Name' THEN CASE @direction2 WHEN 'A' THEN name_order ELSE -name_order END
WHEN 'Age' THEN CASE @direction2 WHEN 'A' THEN age_order ELSE -age_order END
ELSE NULL
END
Repeat as many times as is required...
Note: Just because it can be done this way, doesn't mean it should be done this way.