MS Sql: Conditional ORDER BY ASC/DESC 问题 [英] MS Sql: Conditional ORDER BY ASC/DESC Question
问题描述
我想让我的查询中的排序有条件,所以如果它满足条件,它应该按降序排序
I want to to make to make the ordering in my query conditional so if it satisfiess the condition it should be ordered by descending
例如:
SELECT * FROM Data ORDER BY SortOrder CASE WHEN @Direction = 1 THEN DESC END
推荐答案
不要改变 ASC
或 DESC
,改变正在排序的事物的符号:
Don't change the ASC
or DESC
, change the sign of the thing being sorted-by:
SELECT * FROM table
ORDER BY
CASE WHEN @Direction = 1 THEN -id else id END asc;
OP 询问:
伙计们,我不是 SQL 专家,请解释一下 id 和 -id 是什么意思,它控制排序方向吗?
Guys, I am not the SQL Expert, please explain me what means the id and -id, does it controls the ordering direction?
id 就是您要排序的任何列;-id 只是那个的否定,id * -1.如果按多列排序,则需要对每一列求反:
id is just whatever column you're sorting by; -id is just the negation of that, id * -1. If you're sorting by more than one column, you'll need to negate each column:
SELECT * FROM table
ORDER BY
CASE WHEN @Direction = 1 THEN -id else id END
CASE WHEN @Direction = 1 THEN -othercolumn else othercolumn END ;
如果您按非数字列排序,则需要找到使该列为负"的表达式;编写一个函数来做到这一点可能会有所帮助.
If you're ordering by a non numeric column, you'll need to find an expression that makes that column "negative"; writing a function to do that may help.
这篇关于MS Sql: Conditional ORDER BY ASC/DESC 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!