SELECT *
FROM
TableName
WHERE
ORDER BY
CASE @OrderByColumn
WHEN 1 THEN Forename
WHEN 2 THEN Surname
END;
我有一個類似上面的聲明,它讓我動態選擇如何排序查詢結果。但是,如何指定我要訂購的姓氏DESC
和姓氏ASC
?使用Desc/Asc排序的Order By子句聲明
SELECT *
FROM
TableName
WHERE
ORDER BY
CASE @OrderByColumn
WHEN 1 THEN Forename
WHEN 2 THEN Surname
END;
我有一個類似上面的聲明,它讓我動態選擇如何排序查詢結果。但是,如何指定我要訂購的姓氏DESC
和姓氏ASC
?使用Desc/Asc排序的Order By子句聲明
你需要分割你的兩個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
投了贊,謝謝! – 2014-09-20 15:01:59
我可以在我的order by子句中使用多個列嗎?例如'CASE @OrderByColumn WHEN 1 THEN Forename,Date END DESC' – 2014-09-25 22:07:18
@volumeone不是那樣的,沒有。 「CASE」表達式返回單個值,因此您需要在逗號後用第二列重複該情況。 – dasblinkenlight 2014-09-25 23:31:58
您需要在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
另一個例子:
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
請參閱[這篇文章](http://sqlperformance.com/2012/08/t-sql-queries/conditional-order-by)和[這也許是一個有趣的閱讀](http:// blogs。 sqlsentry.com/aaronbertrand/sql-variant-use-case/)。 – 2014-09-20 14:44:32