MS Sql:条件ORDER BY ASC / DESC问题

时间:2009-04-17 01:09:00

标签: sql sql-server sql-order-by

我想使我的查询中的排序有条件,所以如果它满足条件,它应该按降序排序

例如:

SELECT * FROM Data ORDER BY SortOrder CASE WHEN @Direction = 1 THEN DESC END

4 个答案:

答案 0 :(得分:36)

请勿更改ASCDESC,更改正在排序的内容的符号:

SELECT * FROM table 
ORDER BY 
CASE WHEN @Direction = 1 THEN -id else id END asc;

OP问道:

  

伙计们,我不是SQL专家,请解释一下id和-id是什么意思,它是否控制了订购方向?

id就是您要排序的任何列; -id只是否定,id * -1。如果您按多列排序,则需要否定每列:

SELECT * FROM table 
ORDER BY 
CASE WHEN @Direction = 1 THEN -id else id END 
CASE WHEN @Direction = 1 THEN -othercolumn else othercolumn END ;

如果您按非数字列进行排序,则需要找到一个使该列“为负”的表达式;写一个函数来做到这一点可能有所帮助。

答案 1 :(得分:10)

SELECT * 
FROM Data 
ORDER BY 
Case WHEN @Direction = 1 THEN SortOrder END DESC, 
Case WHEN 1=1 THEN SortOrder END

答案 2 :(得分:8)

您还可以使用支持所有列类型的方案:

SELECT <column_list> FROM <table> ORDER BY CASE WHEN @sort_order = 'ASC' AND @sort_column = '<column>' THEN <column> END ASC, CASE WHEN @sort_order = 'DESC' AND @sort_column = '<column>' THEN <column> END DESC

答案 3 :(得分:1)

我做过类似的事情

select productId, InventoryCount, 
    case 
    when @Direction = 1 then InventoryCount 
    else -InventoryCount 
    end as "SortOrder"
order by 3